Handle 404 response in Laravel

0
312
Laravel Framework
Laravel Framework

Laravel framework provides various ways to handle 404 responses for web application.

Prior to Laravel 5.5.10, in order to catch 404 error, we can detect by catching the NotFoundHttpException, which results like this


class Handler extends ExceptionHandler
{
    public function render($request, Exception $exception)
    {
        if ($exception instanceof NotFoundHttpException) {
            return view('404');
        }

        return parent::render($request, $exception);
    }
}

Well, for 404 view-type response, you can just create a 404.blade.php under resources/views/errors, as mentioned on Laravel documentation.
But if you want to response in JSON or custom format, you will need to catch like above. For example,


class Handler extends ExceptionHandler
{
    public function render($request, Exception $exception)
    {
        if ($exception instanceof NotFoundHttpException) {
            return response()->json(['status' => 'error']);
        }

        return parent::render($request, $exception);
    }
}

In version 5.5.10, Laravel provides a special method fallback(),


Route::fallback(function(){
    return view('404');
});

so, if users make request to a non-existing route, it will route to that fallback route handler.
This way looks much more elegant than previous versions. It’s all up to your own decisions.