phplaravelmiddlewarelumen

Custom 404 page in Lumen


I'm new to the Lumen framework and am in the process of creating an app. I've encountered a problem where if a user enters an incorrect URL (for example, http://www.example.com/abuot instead of http://www.example.com/about), I want to display a custom error page. Ideally, this would occur at the middleware level.

I can verify whether the current URL is valid, but I'm unsure how to generate the view within the middleware, as the response()->view() function doesn't seem to work.

Any assistance would be greatly appreciated.


Solution

  • 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.