【问题标题】:Laravel Policies in Controller Constructor控制器构造函数中的 Laravel 策略
【发布时间】:2018-06-06 23:18:56
【问题描述】:

我正在使用策略类来授权一些用户(作者或管理员)更新和删除帖子模型中的记录。这是一个简单的 CRUD。问题是:如何一次对特定方法进行策略检查?例如,我可以在我的 PostController 构造函数中使用中间件来检查用户是否已登录,但我该如何做类似于需要参数的策略的事情呢?

后控制器

public function __construct()
{
  $this->middleware('auth', ['except' => ['index', 'show']]);
}

邮政政策

class PostPolicy
{
  use HandlesAuthorization;

  public function before($user)
  {
    if ($user->hasRole('admin')) {
      return true;
    }
  }

  public function manage($user, $post)
  {
    return $user->id == $post->user_id;
  }
}

AuthServiceProvider

public function boot()
{
  $this->registerPolicies();

  Gate::define('manage-post', 'App\Policies\PostPolicy@manage');
}

我试过了:

$this->middleware('can:manage-post', ['except' => ['index', 'show']]);

但是没有用。

提前致谢。

【问题讨论】:

  • 需要查看您的路线定义

标签: php laravel


【解决方案1】:

我只会注册策略并使用它,而不是单独写出“能力”。

can:manage,post

manage 操作,post 用于门(资源)的路由参数。

Laravel 5.5 Docs - Authorization - Authorizing Actions - via Middleware

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2013-06-09
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    相关资源
    最近更新 更多