定义中间件

要定义新的中间件,我们必须创建中间件类:

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');