dongqing7789 2017-12-26 01:10
浏览 137

Controller构造函数中的Laravel策略

I'm using a Policy Class to authorize some users(authors or admins) to update and delete records from Post Model. It is a simple CRUD. The question is: How can I make a policy check run for specifics methods at once? For example, I can use a middleware in my PostController constructor to check if user is logged, but how can I do something similar to a policy that needs parameters?

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');
}

I tried this:

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

But it didn't work.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douyinzha5820 2017-12-26 01:16
    关注

    I would just register the policy and use that instead of writing out an 'ability' separately.

    can:manage,post
    

    manage the action, post the Route Parameter to use for the gate (resource).

    Laravel 5.5 Docs - Authorization - Authorizing Actions - via Middleware

    评论

报告相同问题?

悬赏问题

  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决