Answer the question
In order to leave comments, you need to log in
How to resolve access rights depending on the user's role?
Hello.
I'll start with a simple example to make it easier to formulate questions.
So, there is an entity Contract with fields:
- number
- date
- manager_id
- Директор (видит все контракты)
- Менеджер (видит только "свои" контракты)
- доступ ко всем контрактам (назначить это разрешение для роли "Директор")
- доступ к "своим" контрактам (назначить это разрешение для роли "Менеджер")
if (User::hasPermission('all_contracts')) {
Contract::all();
} elseif (User::hasPermission('own_contracts')) {
Contract::getByManager(User::getId());
}
- region_id
if (User::hasPermission('all_contracts')) {
Contract::all();
} elseif (User::hasPermission('own_contracts')) {
if (User::hasRole('manager')) {
Contract::getByManager($managerId);
} elseif (User::hasRole('region_manager')) {
Contract::getByRegion(User::getRegionId());
}
}
Answer the question
In order to leave comments, you need to log in
In order not to fence a bunch of methods for sampling for every case of life, I would make a scope that would take the user as an argument and filter the records depending on the permissions. Then the selection of contracts will always be "clean", such as
In the scope, you will already have to prescribe filters for permissions.
Yes, it may not be the best practice, but it works. Theoretically, of course, this has not yet been implemented.
I would advise you to use ready -made packages for such purposes. Then you will have the opportunity to check the rights in the controller methods, and get models that correspond to the rights that you specify (through scopes)
Voters should help you - https://symfony.com/doc/current/security/voters.html
Here is my article just on this topic: Laravel 5. Hierarchical RBAC for the smallest
The package in question allows you not to change the application code at all when adding new roles, create and modify roles very flexibly and use standard Laravel features, including , and in templates.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question