php教程

超轻量级php框架startmvc

Laravel框架基于中间件实现禁止未登录用户访问页面功能示例

更新时间:2020-04-01 18:32:38 作者:startmvc
本文实例讲述了Laravel框架基于中间件实现禁止未登录用户访问页面功能。分享给大家供大

本文实例讲述了Laravel框架基于中间件实现禁止未登录用户访问页面功能。分享给大家供大家参考,具体如下:

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, // 这一行
];

4、使用中间件(一定要把登录路由的放在外面)


Route::group(['middleware' => 'check.login'], function() {内部为,不想让未登录用户进的路由}

5、成功

Laravel 中间件 未登录用户 访问页面