How can I customize 404, 400, and other errors in Laravel 5.6?
I have my error pages listed in the errors folder inside view
How can I customize 404, 400, and other errors in Laravel 5.6?
I have my error pages listed in the errors folder inside view
The error pages in Laravel should be controlled through the class App\Exceptions\Handler
, which is responsible for handling all exceptions in the framework. Within this class we have two methods: report
and render
.
The method that interests us is render
, which is responsible for converting an exception to an HTTP response. This is where we can define our personalized responses. For example, for a response to the 500 error code:
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.500', [], 500);
}
return parent::render($request, $exception);
}
A much more dynamic way to redirect your custom error pages and respond to the exceptions (errors) that occur in your application would be the following:
public function render($request, Exception $e)
{
if($this->isHttpException($e)){
if (view()->exists('errors.'.$e->getStatusCode()))
{
return response()->view('errors.'.$e->getStatusCode(), [], $e->getStatusCode());
}
}
return parent::render($request, $e);
}
This code snippet checks that the exception that is received is HTTP and that the custom view exists before redirecting the user. All this taking into account that the views are located in the directory views/errors/{code}
, as it seems to be your case.
I hope I helped you. You can always consult the official documentation of Laravel that is very well explained: Error Handling in Laravel .