0

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?

Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
Joyal
  • 2,587
  • 3
  • 30
  • 45
  • What is the exact error message you are receiving? Without this we cannot really help you. Please post the contents of your error message. – Fjarlaegur Sep 23 '19 at 13:19
  • When I try to access the role value from a controller (Auth::user()->role) I get the "Undefined index: role" – Joyal Sep 25 '19 at 07:13

2 Answers2

2

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
Joyal
  • 2,587
  • 3
  • 30
  • 45
0

first get user details and then update that user detais like

$user = User::findOrFail(Auth::user()->id);
$user->role  = "director";
$user->save();

try this code

sandip bharadva
  • 629
  • 1
  • 6
  • 19