Using laravel custom 404 page example; In this tutorial you will learn how to easily create custom 404 not found page in laravel app.
While working on a web application errors or more precisely exception can manifest at any time, Laravel framework handles exceptions beautifully; It offers a handy error handler class which looks for almost every errors displayed in Laravel environment and returns an adequate response.
Custom 404 Error Page in Laravel
Generically, you can get the default error response if you configure debug property to false; nevertheless, you can create a custom error handling template. Let’s handle custom errors in Laravel.
- Create 404 View File
- Modify Exceptions Handler
Create 404 View File
For creating custom 404 page in laravel you just need to go to resources/views folder and create a folder named errors. So the location of our 404 page is resources/views/errors/404.blade.php
.
resources\views\errors\404.blade.php
<!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">Page not Fount!</p>
</div>
</div>
</body>
</html>
Modify Exceptions Handler
Now, navigate to app/Exceptions and open Handler.php
file and find the render() method. Then modify the render() method only as follow:
public function render($request, Exception $exception)
{
if ($this->isHttpException($exception)) {
if ($exception->getStatusCode() == 404) {
return response()->view('errors.' . '404', [], 404);
}
}
return parent::render($request, $exception);
}
Now run the project and visit a wrong page or any 404 errors occured then page will redirect and show 404 error message.