A
A
adam_carraway2020-09-11 11:46:02
Laravel
adam_carraway, 2020-09-11 11:46:02

How to set up automatic policies?

I register policy.

protected $policies = [
        Role::class => RolePolicy::class,
        User::class => UserPolicy::class,
        ReferralRule::class => ReferralRulePolicy::class
    ];

The files are located like this
use App\Models\ReferralRule;
use Packages\Admin\Models\User;
use Packages\Admin\Policies\ReferralRulePolicy;
use Packages\Admin\Policies\RolePolicy;
use Packages\Admin\Policies\UserPolicy;

But policies do not automatically work. it is necessary to register in each controller method
$this->authorize('my permission', Model::class);
for them to work. I think that this is due to the fact that my models and policies have such a namespace. I read that you can override the automatic search policy for the model, but I did not quite understand how to do this for my case. I ask for help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-09-11
@adam_carraway

There is no such functionality. in the provider, a simple binding of the model to the policy is prescribed. It has nothing to do with controller methods. This is so that Laravel knows which policy to pull when you pass the model as an argument. The only way to not write the authorize helper everywhere is to specify the connection in the constructor of the resource controller

public function __construct()
{
    $this->authorizeResource(Article::class, 'article');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question