Laravel how to return 404

"Learn how to configure a 404 error page in your Laravel app with an example."

Returning a 404 Error in Laravel

When a user attempts to access a page on your website that doesn't exist, it's important to return a 404 error page. This is not only good for SEO, but also provides a better user experience than the default Laravel error page. In Laravel, this can be achieved by creating a custom 404 page and setting up a few routes to serve it. Below is an example of how to do this.

Create a 404 Page

The first step is to create a 404 page. This can be done by creating a view in your resources/views directory. The view should contain the HTML for your 404 page. For example:

<h1>404 - Page Not Found</h1>

<p>Sorry, the page you are looking for could not be found.</p>

Define a Route to Serve the 404 Page

Once the 404 page is created, you can set up a route to serve it:

Route::any('{all}', function() {
    return view('errors.404');
})->where('all', '.*');
This route will catch any request that doesn't match one of your existing routes, and serve the 404 page. If you have a lot of existing routes, you can add the route above to the bottom of your routes/web.php file to make sure it is the last route evaluated.

Set the 404 Page as the Default Error Page

The final step is to set the 404 page as the default error page. This can be done by editing the render method in your app/Exceptions/Handler.php file to return the 404 page instead of the default error page. For example, the render method may look like this:

public function render($request, Exception $exception)
{
    return parent::render($request, $exception);
}
You can modify it to look like this:

public function render($request, Exception $exception)
{
    if ($exception instanceof NotFoundHttpException) {
        return response()->view('errors.404', [], 404);
    }
    return parent::render($request, $exception);
}
Now when a user attempts to access a page that doesn't exist, Laravel will return your custom 404 page.

Answers (0)