How do I create custom view for errors on Lumen? I tried to create resources/views/errors/404.blade.php
, like what we can do in Laravel 5, but it doesn't work.
Errors are handled within App\Exceptions\Handler
. To display a 404 page change the render()
method to this:
public function render($request, Exception $e)
{
if($e instanceof NotFoundHttpException){
return response(view('errors.404'), 404);
}
return parent::render($request, $e);
}
And add this in the top of the Handler.php file:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
Edit: As @YiJiang points out, the response should not only return the 404 view but also contain the correct status code. Therefore view()
should be wrapped in a response()
call passing in 404
as status code. Like in the edited code above.
The answer by lukasgeiter is almost correct, but the response made with the view
function will always carry the 200
HTTP status code, which is problematic for crawlers or any user agent that relies on it.
The Lumen documentation tries to address this, but the code given does not work because it is copied from Laravel's, and Lumen's stripped down version of the ResponseFactory
class is missing the view
method.
This is the code which I'm currently using.
use Symfony\Component\HttpKernel\Exception\HttpException;
[...]
public function render($request, Exception $e)
{
if ($e instanceof HttpException) {
$status = $e->getStatusCode();
if (view()->exists("errors.$status")) {
return response(view("errors.$status"), $status);
}
}
if (env('APP_DEBUG')) {
return parent::render($request, $e);
} else {
return response(view("errors.500"), 500);
}
}
This assumes you have your errors stored in the errors
directory under your views.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With