According to the official documentation:
The abort function throws an HTTP exception which will be rendered by the exception handler: abort(403)
. View more
What the documentation doesn’t say is that you can also pass either a
Illuminate\Contracts\Support\Responsable::class
or a \Symfony\Component\HttpFoundation\Response::class
instance, as a parameter to the abort()
helper.
So, you could return a JSON response if you want:
The example above will return a 402 response with the following content:
An Illuminate\Http\Exceptions\HttpResponseException::class
is thrown by the abort()
method, and captured by the Illuminate\Foundation\Exceptions::class
As you can see in both cases, if ($e instanceof Responsable)
or if ($e instanceof HttpResponseException)
, the render()
function will just resolve the response that was passed as the first argument to the abort()
helper.
This is the source code for the abort()
helper:
Wrapping up
Using the abort()
method is a clean and nice way to return an early response from anywhere in your application if needed, such as a static view, an error, a JSON response, and so on.