I want to add a custom value (role) to Auth::user()
after successful login.
I added following code in \App\User
protected $attributes = ['role'];
protected $appends = ['role'];
public function getRoleAttribute()
{
return $this->attributes['role'];
}
public function setRoleAttribute($value)
{
$this->attributes['role'] = strtolower($value);
}
and I set role from Auth\LoginController
function authenticated(Request $request, $user)
{
//I find $position based on some calculation
if($position == 1)
{
Auth::user()->role = 'director';
return redirect('supervisors');
}
}
I want to get role in different pages like $role = Auth::user()->role;
(but this returns error)
how can I achieve this?
I found a solution myself.
Since I have to use the 'role' value in different controllers and there is no column in database table to keep the value I had to use session to store the value.
I set role value in session when user is authenticated at Auth\LoginController
function authenticated(Request $request, $user)
{
if(xxxxx)
{
if(xxxx)
{
Auth::user()->role = 'director';
}
else
{
Auth::user()->role = 'manager';
}
}
}
In App\User
public function getRoleAttribute()
{
return Session::get('role', null);
}
public function setRoleAttribute($value)
{
Session::put('role', $value);
}
Now I can access the role value from anywhere using the following code
Auth::user()->role
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments