(编辑:jimmy 日期: 2024/11/20 浏览:2)
本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。