Laravel 5 Create a 404 Page Not Found HTTP Custom Error Exception Handler
Some Exception in PHP tell the HTTP error code generated from the server. For Example 'Page Not Found' have 404 error code and sometime it generated 500 error code which tell the server error.
In Laravel you can create your own custom error pages based on different HTTP status codes.
Create all pages releted to HTTP status code in following path resources/views/errors/
Here a common list of HTTP status code which you face everytime in application :
- 400 for Bad Request
- 403 for Forbidden
- 404 for Not Found
- 408 for Request Timeout
- 408 for Request Timeout
- 500 for Internal Server Error
You can create a view file like 400.blade.php
403.blade.php
404.blade.php
500.blade.php
for this type of HTTP status code .
You can make changes in following path app/Exceptions/Handler.php within render method.
Here we check first if error is http exception then we render custom error pages.
We can check HTTP Exception by $this->isHttpException($e)
mthod.
Now just simply made changes in your Handler.php
by following line of code.
- public function render($request, Exception $e)
- {
- if($this->isHttpException($e)){
- if (view()->exists('errors.'.$e->getStatusCode()))
- {
- return response()->view('errors.'.$e->getStatusCode(), [], $e->getStatusCode());
- }else{
- return response()->view('errors.custom', [], $e->getStatusCode());
- }
- }
- return parent::render($request, $e);
- }
You can also check if request is ajax then you can return json feedback.
- if ($request->ajax()) {
- return response()->json(['error' => 'Not Found'], 404);
- }
You can use switch case too for specific HTTP Status error code.
- if($this->isHttpException($e))
- {
- switch ($e->getStatusCode()) {
- // not found
- case 404:
- return response()->view('errors.404',[],404);
- break;
- // internal server error
- case '500':
- return response()->view('errors.500',[],500);
- break;
- default:
- return $this->renderHttpException($e);
- break;
- }
- }
Now create a page accroding HTTP Status code, here i am creating page 404.blade.php
in following path resources/views/errors/404.blade.php
- <div class="page_content_wrap">
- <div class="content_wrap">
- <div class="text-align-center error-404">
- <h1 class="huge">404</h1>
- <hr class="sm">
- <p><strong>Sorry - Page Not Found!</strong></p>
- <p>The page you are looking for was moved, removed, renamed<br>or might never existed. You stumbled upon a broken link :(</p>
- </div>
- </div>
- </div>