Using Laravel 9 custom 404 error page example tutorial, we will learn how to create custom 404 error pages in laravel application. Follow the following step by step from scratch for how to create custom 404, 500 error pages in laravel.
Download Laravel App
On the console, screen type the following command and hit enter to generate a new laravel project. You can ignore this step if the app is already installed:
composer create-project laravel/laravel --prefer-dist laravel-error-handling
Create Custom 404 Error Page
You need to create blade views for error pages, move to this path resources/views/ inside here create errors folder and within the directory create 404.blade.php file. It will redirect you to the 404 page if you don’t find the associated URL.
Include the following code in resources/views/errors/404.blade.php error 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>
Make Routes
Next step, go to routes folder and open web.php file and add the following routes into file:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('posts', [PostController::class, 'index']);
Create Controller
Next step, open command prompt and execute the following command to create a controller by an artisan:
php artisan make:controller PostController
After that, go to app\Http\Controllers
and open PostController.php file. Then update the following code into PostController.php file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function index()
{
$post = Post::where('id', 0)->first();
if (!$post) {
abort(404);
}
//return view('posts');
}
}
Run Your Application
To test out the 404 custom error template, you need to start the application.
php artisan serve
As you know, 404 errors occur when you visit the non-existed link, so type the wrong URL or you can use the posts url for showing 404 error in the browser’s address bar.
http://127.0.0.1:8000/not
http://127.0.0.1:8000/posts
So, Laravel 9 create custom error page example, we have learned how to create custom page for 404, 500 error in laravel apps. As well as how to use them.