Answer the question
In order to leave comments, you need to log in
How to correctly implement user authorization in Laravel?
There are tables, "usrers", "usres_roles", "users_has_roles".
I made a user registration through a regular form, with the addition of a many to many relationship model. So that when a user registers, he is automatically assigned the "user" role and entered data in the "users_has_roles" table, in the user_id and role_id fields, respectively.
Through the usual Auth::attempt, data is taken only from the "users" table.
How can I correctly implement so that the user is assigned his roles during authorization?
For example, I would like Auth to store the "user_role" field. And already on the basis of the data contained in this field, it would be possible to check the user's access to the page through middleware.
Answer the question
In order to leave comments, you need to log in
Create intermediate tables
user_roles with keys user_id role_id to link roles to users
role_perms with role_id perm_id to link roles to rules
Relation in user to role
public function roles() {
return $this->belongsToMany('App\Models\Role', 'user_roles', 'user_id', 'role_id')
->withPivot('active');
}
public function perms() {
return $this->belongsToMany('App\Models\Perm', 'role_perms', 'role_id', 'perm_id');
}
public function hasPerm($perm_id) {
foreach ($this->roles as $role) {
foreach ($role->perms as $perm) {
if ($perm_id==$perm->id) {
return true; }}}
}
$perms = Perm::get();
foreach ($perms as $perm) {
Gate::define($perm->name, function($user) use($perm) {
return $user->hasPerm($perm->id);
});
}
@can ('CREATE_PROJECT')
<input type="button" value="Создать проект">
@endcan
public function store (ProjectRequest $request) {
//доступ к методу
if (Gate::denies('CREATE_PROJECT')) {
abort(404);
}
}
if($user->hasRole($roleId)){
return $next($request);
}
return redirect('/');
public function hasRole($id) {
return $this->roles->contains('id',$id);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question