B
B
BonBon Slick2017-01-22 12:53:14
Laravel
BonBon Slick, 2017-01-22 12:53:14

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

2 answer(s)
M
Mysterion, 2017-01-22
@BonBonSlick

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"
}

It can be through relationships. In the User model:
public function roles() {
    return $this->hasMany('App\Models\Roles');
}

And in the controller:
$role = User::find($user_id)->roles()->where('role', 'news_edit')->first();

D
D3lphi, 2017-01-22
@D3lphi

Here is a great library: https://cartalyst.com/manual/sentinel/2.0
There is integration with Laravel

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question