How to make Laravel 5 return 404 status code

Very simple, I assumed you use Laravel v5++ just go to

app > Exceptions > Handler.php

See the picture as below:

enter image description here

And modify the codes from:

public function render($request, Exception $e)
{
    return parent::render($request, $e);
}

to

public function render($request, Exception $e)
{
    if ($e instanceof MethodNotAllowedHttpException)
    {
        abort(404);
    }
    return parent::render($request, $e);
}

Then, do not forget to add 404.blade.php page in errors folder:

enter image description here

Well, you can customise by yourself the 404 page in 404.blade.php.


Note

This case only when you run the URL were not listed as in the routes. You may find in web.php file.

In case you need to call by custom, just call in the controller like below:

public function show_me()
{
   abort(404);  //404 page
}

Hope it helps!


you may use the abort helper:

abort(404);

While I don't know why abort is not returning the 404 status as it is suppose to, I did find a solution that will make Laravel return a 404 status:

Here is what I did:

else {
    $data['title'] = '404';
    $data['name'] = 'Page not found';
    return response()->view('errors.404',$data,404);
}

This actually works better for my purposes because it doesn't mess with the contents of my 404.blade like the abort does.


If you want to return JSON instead of a view, you can call this in your controller:

return response(['error'=>true,'error-msg'=>$msg],404);

Tags:

Laravel 5