用户授权policy
-
定义策略类
php artisan make:policy PostPolicy
app/Policies/PostPolicy.php
public function update(User $user,Post $post){ return $user->id === $post->user_id; } public function delete(User $user,Post $post){ return $user->id === $post->user_id; }
-
注册策略类和模型关联
app/Providers/AuthServiceProvider.php
protected $policies = [ // 'App\Model' => 'App\Policies\ModelPolicy', 'App\Post' => 'App\Policies\PostPolicy' ];
resources/views/post/show.blade.php
@can('update',$post) <!-- 编辑操作 --> @endcan @can('delete',$post) <!-- 删除操作 --> @endcan
-
策略判断
$this->authorize('update',$post);