Laravel中间件实现的目的是过滤http请求,如果通过了过滤就会往下执行。
1、先生成一个数据库迁移
php artisan make:migration user_table_is_admin;
2、编辑数据库迁移文件
class userTableIsAdmin extend Migration{
public function up(){
Schema::create("users",function(Blueprient $table)){
$table->boolean('isAdmin')->default(0);
}
}
public function down(){
Schema::drop("users");
}
}
3、生成中间件
php artisan make:middleware isAdminMiddleWare
4、编辑中间件内容
class isAdminMiddleWare{
public function handle($request,Closure $next){
if(Auth::guest()||!Auth::user()->isAdmin()){
return redirect('/',301)->with('message','login')
}
return $next($request);
}
}
5、把中间件添加到app/http/Kernel.php中
protect $routeMiddleWares=[
'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,
'admin' => \App\Http\Middleware\AdminMiddleware::class,
]