Laravel 5.5 - create custom 404 error page


In this article, i will let you know how to create custom error page in laravel 5.5 application. If you know well laravel then you know we can simply create error pages in errors directory of views folder, but in this article i will show you to create custom 404 error page using route and right way of SEO friendly.

Here, i will explain how to handle laravel exception and manage all custom errors page on right way of seo too. So let's simply follow bellow step to do this:

Step 1: Change on Handler.php File

In first step we will add route exception wise so let's open Handler.php file and make it like as bellow:

app/Exceptions/Handler.php

<?php


namespace App\Exceptions;


use Exception;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;


class Handler extends ExceptionHandler

{

...


public function report(Exception $exception)

{

parent::report($exception);

}


public function render($request, Exception $exception)

{

if($this->isHttpException($exception)){

switch ($exception->getStatusCode()) {

case 404:

return redirect()->route('404');

break;

case 405:

return redirect()->route('405');

break;

}

}


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

}

}

Step 2: Add Error Route

In second step, we have to create new route 404 and 405 for example, if we manage it this way then it is perfect for SEO so let's add both route on web.php file.

routes/web.php

Route::get('404',['as'=>'404','uses'=>'ErrorHandlerController@errorCode404']);

Route::get('405',['as'=>'405','uses'=>'ErrorHandlerController@errorCode405']);

Step 3: Add Controller

In third step we will create new controller "ErrorHandlerController", in this controller we will define method of all error code that we want. So let's create new controller and put bellow code:

app/Http/Controllers/ErrorHandlerController.php

<?php


namespace App\Http\Controllers;

use Illuminate\Http\Request;


class ErrorHandlerController extends Controller

{


public function errorCode404()

{

return view('errors.404');

}


public function errorCode405()

{

return view('errors.405');

}

}

Step 4: Add Blade Files

Here in last step, we will add two blade file for those two error, 404.blade.php and 405.blade.php file. So let's create both file:

resources/views/errors/404.blade.php

<!DOCTYPE html>

<html>

<head>

<title>404 Page Not Found Error</title>

</head>

<body>

<h1>Sorry, Page Not Found 404</h1>

</body>

</html>

resources/views/errors/405.blade.php

<!DOCTYPE html>

<html>

<head>

<title>405 Page Not Found Error</title>

</head>

<body>

<h1>Sorry, Page Not Found 405</h1>

</body>

</html>

Now you can check simply and it works.

I hope you found best solution...


September 27, 2017 | 3277 Viewer | Category : PHP Laravel

Related Posts: