Return a 404 response in Laravel
June 27, 2022 ‐ 2 min read
Laravel has multiple options for you to a 404 response. Some more generic, some pretty specific to querying for a particular model.
Using abort()
One pretty easy method is by using the abort()
helper to raise an exception which will be handled by the Laravel exception handler.
All you need for this is to call the abort()
method with the 404 status code as its argument.
<?php
public function show(Request $request, $id)
{
$model = Model::find($id);
if ($questionModel === null) {
abort(404);
}
}
Manually set the status code
Another option would be to return a response with a manually set http status, so 404 in our case.
<?php
public function show(Request $request, $id)
{
$model = Model::find($id);
if ($questionModel === null) {
return response([], 404);
}
}
This approach works also well if we wish to return a json response with status code. In such a case we can chain the json()
method which sets the correct Content-Type
header for us as well.
<?php
public function show(Request $request, $id)
{
$model = Model::find($id);
if ($questionModel === null) {
return response()->json(['error' => true, 'data' => []], 404);
}
}
Find or fail with 404
If you are specifically checking whether a model exists, and return a 404 based on this, you can more conveniently reach for the findOrFail()
method.
If the model doesn't exist in our queryset this throws a ModelNotFoundException
which will automatically cause a 404 HTTP response to be returned.
<?php
public function show(Request $request, $id)
{
$model = Model::findOrFail($id);
}