How to return page 404 Laravel

How to restore a 404 page in Laravel: a step-by-step guide with an example.

Returning a 404 Error Page with Laravel

Laravel makes it easy to return a custom 404 error page if a page or resource is not found. This can be helpful when creating custom 404 pages, such as when a user looks for a page or resource that no longer exists. Here's an example of how to return a custom 404 error page using Laravel.


// First, create a custom 404 error page in resources/views/errors/404.blade.php

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="alert alert-danger">
                    <h2>Page Not Found</h2>
                    <p>We're sorry, but the page or resource you requested could not be found.</p>
                </div>
            </div>
        </div>
    </div>
@endsection

Next, create an exception handler in app/Exceptions/Handler.php. Add the following code to the render method:


public function render($request, Exception $exception)
{
    if ($exception instanceof SymfonyComponentHttpKernelExceptionNotFoundHttpException)
    {
        return response()->view('errors.404', [], 404);
    }

    return parent::render($request, $exception);
}

This will tell Laravel to look for the 404.blade.php file in the resources/views/errors folder, and return it when a NotFoundHttpException is encountered. This way, when a user requests a page or resource that does not exist, they will be shown your custom 404 error page.

Answers (0)