Laravel 中间件

创建中间件

php artisan make:middleware check

创建之后需要在Kernel.php里注册中间件

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        ...........
        'check' => \App\Http\Middleware\check::class
    ];

中间件的登录

  • 方法一
    public function handle($request, Closure $next)
    {
        if (!\Auth::check) {
            return redirect('login');
        }
        return $next($request);
    }
  • 方法二
    public function handle($request, Closure $next)
    {
        if (!request()->session()->has('uid')) {
            return redirect('login');
        }
        return $next($request);
    }

在路由里使用中间件

  • 方法一
Route::get('index','index@index')->middleware('check');
  • 方法二
    将路由放进群组
Route::group(['middleware'=>['check']],function(){
    Route::get('/','index@index');
    Route::get('show','index@show');
    Route::get('add','index@add');
});
  • 方法三
    对于多级权限
Route::group(['middleware'=>'user_check'],function(){
    Route::get('index','index@index');
    Route::group(['middleware'=>'admin_check'],function(){
        Route::get('newsview','index@newsview');
     })
})

你可能感兴趣的:(Laravel 中间件)