Home / Snippets / How to Make Laravel 8 Return 404 Status Code
How to Make Laravel 8 Return 404 Status Code cover

How to Make Laravel 8 Return 404 Status Code

14.9K

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this