Posts Learn Components Snippets Categories Tags Tools About
/

How to Make Laravel 8 Return 404 Status Code

Learn the ways to return 404 status code from laravel application to indicate when something is not found

Created on Aug 06, 2021

14852 views

There are several ways to return 404 status code in Laravel and you can refer to all of them from the code example below.

1 - Return 404 When Querying Model
When querying the model using "findOrFail($x)" or "firstOrFail()" it can automatically return a not found record.
public function show($id) {
    $post = Post::findOrFail($id);
    $firstPost = Post::firstOrFail();
}

2 - Use abort(404)
The second way is to use "abort(404)" from the location of the code you want it to abort. Having this function will give the 404 status code of the page not found.
public function show($id) {
    // your other code

    abort(404);
}

3 - Using Custom Response 
The third way is to return a response with 404 status code.
public function show($id) {
    // your other code

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

4 - Return Custom 404 View
Finally, if you have custom 404 then you can return the views with the 404 status code.
public function show($id) {
    // your other code

    if ($errorIsTrue) {
        return response()->view('errors.404', ['error' => 'Not Found'], 404);
    }
}

Those are the ways to return 404 status code from your Laravel app, if you have other ways do share it in the comments down below.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Make Laravel 8 Return 404 Status Code

)