Laravel’s abort() helper explained
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:
<?php | |
abort( | |
response()->json(['message' => 'Ooops!.'], 402) | |
); |
The example above will return a 402 response with the following content:
{ | |
"message": "Ooops!." | |
} |
An Illuminate\Http\Exceptions\HttpResponseException::class
is thrown by the abort()
method, and captured by the Illuminate\Foundation\Exceptions::class
<?php | |
class Handler implements ExceptionHandlerContract | |
{ | |
//... | |
public function render($request, Exception $e) | |
{ | |
if (method_exists($e, 'render') && $response = $e->render($request)) { | |
return Router::toResponse($request, $response); | |
} elseif ($e instanceof Responsable) { | |
return $e->toResponse($request); | |
} | |
$e = $this->prepareException($e); | |
if ($e instanceof HttpResponseException) { | |
return $e->getResponse(); | |
} elseif ($e instanceof AuthenticationException) { | |
return $this->unauthenticated($request, $e); | |
} elseif ($e instanceof ValidationException) { | |
return $this->convertValidationExceptionToResponse($e, $request); | |
} | |
return $request->expectsJson() | |
? $this->prepareJsonResponse($request, $e) | |
: $this->prepareResponse($request, $e); | |
} | |
} |
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:
<?php | |
if (! function_exists('abort')) { | |
/** | |
* Throw an HttpException with the given data. | |
* | |
* @param \Symfony\Component\HttpFoundation\Response|\Illuminate\Contracts\Support\Responsable|int $code | |
* @param string $message | |
* @param array $headers | |
* @return void | |
* | |
* @throws \Symfony\Component\HttpKernel\Exception\HttpException | |
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException | |
*/ | |
function abort($code, $message = '', array $headers = []) | |
{ | |
if ($code instanceof Response) { | |
throw new HttpResponseException($code); | |
} elseif ($code instanceof Responsable) { | |
throw new HttpResponseException($code->toResponse(request())); | |
} | |
app()->abort($code, $message, $headers); | |
} | |
} |
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.