Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom 404 page in Lumen

Tags:

laravel

lumen

I'm new to Lumen and want to create an app with this framework. Now I have the problem that if some user enters a wrong url => http://www.example.com/abuot (wrong) => http://www.example.com/about (right), I want to present a custom error page and it would be ideal happen within the middleware level.

Furthermore, I am able to check if the current url is valid or not, but I am not sure how can I "make" the view within the middleware, the response()->view() won't work.

Would be awesome if somebody can help.

like image 806
what Avatar asked Feb 05 '16 03:02

what


2 Answers

Seeing as errors are handled in App\Exceptions\Handler, this is the best place to deal with them.

If you are only after a custom 404 error page, then you could do this quite easily:

Add this line up the top of the Handler file:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

Alter the render function to look like so:

public function render($request, Exception $e)
{
    if($e instanceof NotFoundHttpException){
        return response(view("errors.404"), 404);
    }
    return parent::render($request, $e);
}

This assumes your custom 404 page is stored in an errors folder within your views, and will return the custom error page along with a 404 status code.

like image 74
James Avatar answered Nov 16 '22 18:11

James


You may want to add this so that when for example blade blows up the error page hander will not throw a PHP error.

public function render($request, Exception $exception)
 {
   if (method_exists('Exception','getStatusCode')){

     if($exception->getStatusCode() == 404){
       return response(view("errors.404"), 404);
     }

     if($exception->getStatusCode() == 500){
       return response(view("errors.500"), 404);
     }
   }
   return parent::render($request, $exception);
 }
like image 1
Mark Gregory Avatar answered Nov 16 '22 19:11

Mark Gregory