场景:当前用户创建的订单,只能当前用户自己看,可以通过授权策略类(Policy)来实现
1.php artisan make:policy OrderPolicy
成功后,默认只有一个构造方法.因为涉及到用户 ,订单,所以要注入用户与订单.只有当二者关联ID相等时才算通过.
class OrderPolicy{ use HandlesAuthorization; public function own(User $user, Order $order) { return $order->user_id == $user->id; }}
2.在控制器中使用方法如下:
$this->authorize('own', $order);
3.由于5.8的版本可以配置自动加载,所以不需要再注册policy
porviders/AuthServiceProvide.php
class AuthServiceProvider extends ServiceProvider{ /** * The policy mappings for the application. * * @var array */ protected $policies = [ // 'App\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Gate::guessPolicyNamesUsing(function($class){ return '\\App\\Policies\\'.class_basename($class).'Policy'; }); }}
posted on 2019-05-19 10:27 阅读( ...) 评论( ...)