Laravel send to 404 page | redirect to 404 page automatically at Laravel | how to show 404 page if route not found in Laravel

In Laravel, you can set up a custom 404 page to be displayed when a route is not found or when a resource is not found in your application. Laravel provides a simple way to do this.

  1. Create a Custom 404 Page:

    First, you'll need to create a custom 404 Blade view file that will be displayed when a 404 error occurs. Typically, this file is named 404.blade.php and is placed in the resources/views/errors directory.

    Create a Blade view file for your custom 404 page:

    shell
  • mkdir -p resources/views/errors touch resources/views/errors/404.blade.php

    Edit the 404.blade.php file to design your custom 404 page as you like.

  • Handling 404 Errors:

    Laravel automatically handles 404 errors for you. When a route or resource is not found, Laravel will trigger a 404 error and display the default 404 page, which is defined in the resources/views/errors/404.blade.php file.

    You can customize the content and design of this Blade view file to match your application's style and branding.

    If you want to customize the behavior of the 404 page further, you can do so by modifying the app/Exceptions/Handler.php file in your Laravel application. Specifically, you can customize the render method to handle 404 errors differently:

    php
    1. // app/Exceptions/Handler.php public function render($request, Throwable $exception) { if ($exception instanceof NotFoundHttpException) { return response()->view('errors.404', [], 404); } return parent::render($request, $exception); }

      In this example, we're checking if the exception is an instance of NotFoundHttpException (which represents a 404 error), and if it is, we return a custom 404 Blade view with a 404 HTTP response code.

      This way, you can have more control over the 404 error handling in your Laravel application.

    2. Testing the Custom 404 Page:

      To test your custom 404 page, simply visit a URL that doesn't exist in your application. Laravel will automatically display your custom 404 page.

    That's it! You've set up a custom 404 page in Laravel and configured it to be displayed when a route or resource is not found.

    Comments