定義中介軟體

要定義新的中介軟體,我們必須建立中介軟體類:

class AuthenticationMiddleware
{
    //this method will execute when the middleware will be triggered
    public function handle ( $request, Closure $next )
    {
        if ( ! Auth::user() )
        {
            return redirect('login');
        }

        return $next($request);
    }
}

然後我們必須註冊中介軟體:如果中介軟體應該繫結到應用程式的所有路由,我們應該將它新增到 app/Http/Kernel.php 的中介軟體屬性:

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\AuthenticationMiddleware::class
];

如果我們只想將中介軟體與某些路由相關聯,我們可以將其新增到 $routeMiddleware

//register the middleware as a 'route middleware' giving it the name of 'custom_auth'
protected $routeMiddleware = [
    'custom_auth' => \App\Http\Middleware\AuthenticationMiddleware::class
];

然後將它繫結到單個路由,如下所示:

//bind the middleware to the admin_page route, so that it will be executed for that route
Route::get('admin_page', 'AdminController@index')->middleware('custom_auth');