Gates是一个闭包函数,用于判断用户是否有权限执行某个动作。定义门通常定义在App\Providers\AuthServiceProvider中。Gates的第一个参数是用户实例,支持可选参数,比如Eloquent模型:publicfunctionboot(){$this->registerPolicies();//定义编辑设置的权限Gate::define('edit-settings',function($user){return$user->isAdmin;});//定义更新帖子的权限Gate::define('update-post',function($user,$post){return$user->id===$post->user_id;});}publicfunctionboot(){$this->registerPolicies();Gate::define('update-post','App\Policies\PostPolicy@update');}使用if(Gate::allows('edit-settings')){//当前用户可以编辑设置}if(Gate::allows('update-post',$post)){//当前用户可以更新帖子}if(Gate::denies('update-post',$post)){//当前用户不能更新帖子}if(Gate::forUser($user)->allows('update-post',$post)){//指定用户可以更新帖子}if(Gate::forUser($user)->denies('update-post',$post)){//指定用户不能更新帖子}参数上下文Gate::define('create-post',function($user,$category,$extraFlag){return$category->组>3&&$extraFlag===true;});如果(门::检查('创建位置t',[$category,$extraFlag])){//用户可以创建帖子...}授权响应useIlluminate\Support\Facades\Gate;useIlluminate\Auth\Access\Response;Gate::define('edit-settings',function($user){return$user->isAdmin?Response::allow():Response::deny('Youmustbeasuperadministrator.');});//检查得到GateReturnedfullauthorizationresponse$response=Gate::inspect('edit-settings',$post);if($response->allowed()){//当前操作被授权...}else{echo$response->message();}授权拦截//在所有其他授权检查之前执行Gate::before(function($user,$ability){if($user->isSuperAdmin()){returntrue;}});//在所有其他授权检查之后执行Gate::after(function($user,$ability,$result,$arguments){if($user->isSuperAdmin()){returntrue;}});
