E
E
evgenin2020-05-06 23:26:22
Laravel
evgenin, 2020-05-06 23:26:22

How to make a generic Laravel Policy?

Tell me how to make a universal Policy to limit any model without creating different Policies for each model, so that the restriction on create from the list is taken into account

Example:
There is an array with limits, read the model from it and adjust the Policy

array(
'Post' => 30 //  30 записей максимум
'Products' => 100 // 100 записей максимум
);


The end result should be:
UniversalPolicy

instead of
PostPolicy
ProductsPolicy

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-05-07
@jazzus

With Gate . Write the desired rule in AuthServiceProvider and call it via Gate::allows. But I wouldn't do that. Because most likely, policies will be needed and there is no point in duplicating checks. Or the logic for certain models will change and you will have to rewrite all the checks instead of fixing one policy. Well, policy checks look more interesting. Therefore, the policy is better, without the UniversalPolicy of course, but as it is written in Laravel - separately for each model. Because that is their point. And remove the original information in the configs (numbers or whatever you have). You can also remove the verification code into your class and call it in policies, but this is if $user->posts()->count() is not there < config('post.limit') because this is not code duplication

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question