1、在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,
];
2、每一条对应一个中间件,以最后一条为例,在对应目录App\Http\Middleware\下建立文件CheckLogin.php,文件内容举例如下:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckLogin{
public function handle($request,Closure $next){
//$http_referer=$_SERVER['HTTP_REFERER'];
$member=$request->session()->get('member','');
if($member==''){
return redirect('admin/login');
}
return $next($request);
}
}
3、在路由文件中写入中间件routes.php:
Route::group(['middleware'=>'check.login'],function(){
Route::get('/admin', function () {
return view('admin.index');
});
});
其中check.login是根据Kernel.php中的配置名称而来,这样,我们的laravel中间件便初步配置好了。