Home  >  Article  >  PHP Framework  >  How to better implement 404 response with Laravel 5.5+ framework

How to better implement 404 response with Laravel 5.5+ framework

不言
不言Original
2018-09-10 14:48:592005browse

How to implement 404 page? There are actually many methods. Next, this article will introduce to you how to use the Laravel 5.5 framework to better implement 404 response. Without further ado, let us take a look at the specific content.

Laravel 5.5.10 encapsulates two useful router methods that can help us provide better 404 pages to our users. Now, when a 404 exception is thrown, Laravel will display a beautiful 404.blade.php view file that you can customize to display to the user UI, but in this view, you do not have access session, cookie, authentication (auth), etc...

In laravel 5.5.10, we have a new Route::fallback() Method used to define the route that Laravel falls back on when no other route matches the request.

Route::fallback(function () {
    return 'Sorry' . auth()->user()->name . '! This page does not exist.';
});

So, now we can use an app layout with a normal page and footer, instead of a simple 404 view, while still displaying a friendly prompt message to the user.

Route::fallback(function() {
    return response()->view('notFound', [], 404);
});
@extends('layout.app')

@section('content')
    <h3>Sorry! this page doesn't exist.</h3>
@stop

When Laravel renders this fallback route, all middleware will be run, so when you define the fallback route in the web.php routing file, all The middleware in the web middleware group will be executed, so that we can obtain the session data.

API Interface Description

Now when you click on /non-existing-page, you will see the view defined in the fallback route, even when you click /api/non-existing-endpoint, if you don't want to provide this interface, you can define the JSON response in the api fallback route, let's go to the api. Define another fallback route in the php routing file:

Route::fallback(function() {
    return response()->json(['message' => 'Not Found!]);
});

Since the api middleware group has the /api prefix, all the fallback routes have the /api prefix Undefined routes will enter the fallback route in the api.php routing file, not the one defined in the web.php routing file.

Using abort(404) and ModelNotFound exceptions

When using abort(404), a NotFoundHttpException will be thrown, and the processor will Render the 404.blade.php view file for us, and the same ModelNotFoundException exception will be handled in the same way, so how should we handle it so that we can render the fallback better? What about a routed view instead of a normal view?

class Handler extends ExceptionHandler
{
    public function render($request, Exception $exception)
    {
        if ($exception instanceof NotFoundHttpException) {
            return Route::responseWithRoute('fallback');
        }

        if ($exception instanceof ModelNotFoundException) {
            return Route::responseWithRoute('fallback');
        }

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

Route::respondWithRoute('fallback') Go back and run a route named fallback. We can name the fallback route as follows:

Route::fallback(function() {
    return response()->view('notFound', [], 404);
})->name('fallback');

Even, you can specify fallback routes for specific resources:

if ($exception instanceof ModelNotFoundException) {
    return $exception->getModel() == Server::class
                ? Route::respondWithRoute('serverFallback') 
                : Route::respondWithRoute('fallback');
}

Now we need to define this fallback route in the routing file:

Route::fallback(function(){
    return 'We could not find this server, there are other '. auth()->user()->servers()->count() . ' under your account ......';
})->name('serverFallback');

Related recommendations:

mac mamp ngiux laravel framework reports 404 error

How to implement Laravel 5.5 responsive interface

The above is the detailed content of How to better implement 404 response with Laravel 5.5+ framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn