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

13.4K

2 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

Ahmad Aziz

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 ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this