 1. 文档 在开发程序时, 请查看对应版本的手册 中间件 | 基础组件 | Laravel 5.8 中文文档 路由 | 基础组件 | Laravel 5.8 中文文档 laravel使用中间件实现禁止未登录用户访问页面_snow_small的博客-CSDN博客 2. 整理输出 环境交代 版本: laravel 5.8 2.1 认证[自定义的中间件] 1、生成中间件 [root@localhost MRedis]# php artisan make:middleware CheckLogin Middleware created successfully. 2、实现中间件 app\http\middleware\CheckLogin.php public function handle($request, Closure $next) { if (!session('user')) { return redirect('login');//具体操作, 可自行定义 } return $next($request); } 3、注册中间件 在app\http\kernel.php下,添加的为最后一行 protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'check.login' => \App\Http\Middleware\CheckLogin::class, // 这一行, key自行命令 ]; 4、使用中间件 Note: 一定要把登录路由的放在外面, 否则会一直登录不上 Route::post('/register', 'Web\UserController@register'); Route::post('/login', 'Web\UserController@login'); Route::middleware(['check.login'])->group(function () { // 内部为,不想让未登录用户进的路由, 例如下方: Route::match(['get', 'post'], '/logout', 'Web\UserController@logout'); Route::get('/flight/list', 'Web\FlightController@getList'); Route::get('/flight/{id}', 'Web\FlightController@getDetail'); //... }); 5、测试是否成功 多测试之后即可, 发现已经生效 http://roast.test/flight/1 跳转到Route::post('/login', 'Web\UserController@login');对应的响应 后续补充 ... |