Answer the question
In order to leave comments, you need to log in
What is the best way to implement Laravel user roles?
Suppose I have 10 roles or more, it is possible to create new ones. Rummaged in open source projects, there is nothing of the kind. When creating a role, you need to choose its functionality, adding, editing, visiting which pages, etc. All this is written to the database of the role by type can_delete_products = 1 , etc. And now the most important thing, if I understood everything correctly, then for each function it is necessary to check whether the user has permission to do this. I.e. create a middleware where the user role will be taken and its capabilities will be checked. It's like that? Or who knows easier? Who did what? What do you recommend?
Answer the question
In order to leave comments, you need to log in
If you do not want to use ready-made solutions, then the most primitive option is:
1) Create a role column in the table with users. Write the user's role into it.
2) Create a roles table with user_id and permissions columns, for example.
3) You can specify access flags in the permissions column. Or in one record all rights to enumerate or several records with the rights for one user to do.
4) In the controller methods, check the availability of rights for the user in the roles table. You can use the same Eloquent ORM:
$role = Roles::where(['user_id' => $user_id, 'role' => 'news_edit'])->first();
if($role) {
// есть разрешение "news_edit"
}
public function roles() {
return $this->hasMany('App\Models\Roles');
}
$role = User::find($user_id)->roles()->where('role', 'news_edit')->first();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question