1
votes

I have three table in database. one is users and second one is role and other is user_role.

in role table has id and name.

in user_role table has user_id and roll_id.

now I want to set session when user will log in to app. llike Auth::user()->roll

1
You don't set the session but attach a role to the user... When you register a user then you can set the role for that user to be whatever you like. Or if you have some admin panel then an admin can assign the role to that user. This is the way how it is done. Or you have something else on your mind?lewis4u
but is it possible to show the roll in session?Anwarul Islam
When you assign the role to a user then you can get it always...just call Auth::user()->role or auth()->user()->rolelewis4u
I didn't assign role in users table but I did relation users table to roles table now how can I get data in session from that tableAnwarul Islam

1 Answers

1
votes

Create relationship in User model

public function roles()
{
    return $this->belongsToMany(Role::class);
}

Create relationship in Role model

public function users()
{
    return $this->belongsToMany(User::class);
}

Then you can attatch a role to a user like this:

Auth::user()->roles()->attach(id_of_the_role_from_roles_table);

and that will create a new entry in pivot table role_user and then you can make a function in user model

public function hasRole($role)
{
    return $this->roles->contains('id', $role);
}

and you can call it where ever you want in your code. For example:

Auth::user()->hasRole(1);

That will return true or false and then you can do something with that info.