Controller构造函数中的Laravel策略

问题描述 投票:1回答:1

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

控制器后

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

PostPolicy

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个回答
0
投票

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

can:manage,post

manage动作,post路径参数用于门(资源)。

Laravel 5.5 Docs - Authorization - Authorizing Actions - via Middleware

© www.soinside.com 2019 - 2024. All rights reserved.