1.方法一 直接在AuthServiceProvider 中定义闭包,比较灵活
namespace AppProviders; ... class AuthServiceProvider extends ServiceProvider { ... public function boot(GateContract $gate) { parent::registerPolicies($gate); //使用闭包定义授权能力 $gate->define('update-post', function($user, $post){ return $user->id == $post->user_id; }); //使用类函数定义 $gate->define('update-post', 'PostPolicy@update'); } }
namespace AppHttpControllers; ... //在控制器中检验授权 class PostController extends Controller { public function show($id) { //auth()->logout(); auth()->loginUsingId(3); $post = Post::findOrFail($id); // if(Gate::denies('show-post', $post)){ // abort(403, 'sorry, not sorry!'); // } //$this->authorize('update-post', $post); return view('posts.show', compact('post')); } }
//在view中检验授权,如果通过才显示update链接
<h2>{{$post->title}}</h2> @can('update-post', $post) <a href=#>update</a> @endcan
2.方法二 ,注册策略类来实现
建立policy
php artisan make:policy PostPolicy
注册 模型 =>策略
namespace AppProviders; ... class AuthServiceProvider extends ServiceProvider { protected $policies = [ // 'AppModel' => 'AppPoliciesModelPolicy', AppPost::class => AppPoliciesPostPolicy::class, ];
定义类策略函数
namespace AppPolicies; use AppUser; use AppPost; class PostPolicy { //可以建立多个检验方法对应不同场景 public function update(User $user, Post $post) { return $user->id == $post->user_id; } }
使用方法同上。