在項目根目錄下使用:php artisan make:middleware 中間件名稱Middleware命令創(chuàng)建中間件
- 創(chuàng)建中間件
php artisan make:middleware中間件名字Middleare. - 在中間件中寫下規(guī)則,主要就是進行判斷是否登錄,當然也別忘了引入命名空間,如下例:
public function handle($request, Closure $next)
{
//判斷是否登陸,如未登錄則重定向到登陸頁
if(empty(\Session::get('admin'))) {
return redirect('/login');
}
//如已登陸則執(zhí)行下一步
return $next($request);
}
- 在
Kemel.php文件中中間件添加到局部中間件中,如下例:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
//添加的中間件 Admin
'Admin' => \App\Http\Middleware\AdminMiddleware::class,
];
- 在路由里加入中間件,除了登錄、注冊和執(zhí)行登錄方法寫到中間件外面,其余的方法都應該寫入到中間件里面,如下例:
Route::group(['domain' => 'www.wang.com'], function () {
//登陸 寫在中間件外面
Route::resource('index','User\UserController');
//注冊 寫在中間件外面
Route::resource('create','User\UserController@create');
//執(zhí)行登陸 寫在中間件外面
Route::resource('login','User\UserController@login');
//驗證是否登陸中間件
Route::group(['middleware' => 'Admin'],function(){
//列表
Route::resource('show','User\UserController@show');
//修改
Route::resource('edit','User\UserController@edit');
//執(zhí)行修改
Route::resource('update','User\UserController');
//刪除
Route::resource('destroy','User\UserController@destroy');
});
});