How to change/customize 404 page in Laravel

Laravel is a framework comes with pre-defined blades for authentication pages and 404 page. However, we can change or customize the original blades you already have. We can either create a new 404 page blade from scratch or edit an original page.

Create New Custom 404 Page

Step 1: Create new 404 blade file

You can create new blade views for error pages, and place it to the path resources/views/. Here you can create an errors folder and within the directory create 404.blade.php file. This will redirect you to the 404 page if you don’t find the associated URL. You can add in it whatever you want to appear on the 404 error page in Laravel.

In addition, you can also create other error pages for 403, 419, 500, and 255 exceptions. You may add the following code in the 404 blade file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>404 Custom Error Page Example</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="alert alert-danger text-center">
            <h2 class="display-3">404</h2>
            <p class="display-5">Oops! Something is wrong.</p>
        </div>
    </div>
</body>
</html>

Step 2: Edit Handler.php file

You can go to app\Exceptions\Handler.php and replace the render function with code below.

  public function render($request, Throwable $exception)
    {
        if ($exception instanceof AccessDeniedHttpException) {
            return response(view('errors.404'), 404);
        }
        return parent::render($request, $exception);
    }

If you do not have 404.blade.php file, you can create custom 404 page in Laravel with the following command.

You can add multiple if conditions for other exceptions as well. For example, the 403, 419, 500, and 215 exceptions. Then return the corresponding view blade for the particular error display.

 php artisan vendor:publish --tag=laravel-errors