How to show 404 page if route not found in laravel?

Member

by dana , in category: PHP Frameworks , 6 months ago

How to show 404 page if route not found in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 6 months ago

@dana 

To show a 404 page if a route is not found in Laravel, you can follow these steps:

  1. Open the app/Exceptions/Handler.php file.
  2. Locate the render method in the class.
  3. Inside the render method, add the following code snippet:
1
2
3
if ($exception instanceof SymfonyComponentHttpKernelExceptionNotFoundHttpException) {
    return response()->view('errors.404', [], 404);
}


This code checks if the exception is an instance of NotFoundHttpException class, which occurs when a route is not found. If it is, it returns a view named errors.404 with a 404 status code.

  1. Create a 404.blade.php file in the resources/views/errors/ directory. This file will contain the content of your 404 page.
  2. Customize the content of the 404.blade.php file to match your application's design and requirements.


Now, whenever a route is not found, Laravel will automatically display the 404.blade.php view, showing a 404 page to the user.