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?

2
  • What is the exact error message you are receiving? Without this we cannot really help you. Please post the contents of your error message. Commented Sep 23, 2019 at 13:19
  • When I try to access the role value from a controller (Auth::user()->role) I get the "Undefined index: role" Commented Sep 25, 2019 at 7:13

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

thanks for your answer but I don't have 'role' column in users table. role is a custom attribute, I need to set it after user login.
i think you can achive this by using one variable in your user model
and after login you can access that variable and set it's value whatever you want
please refer this link this will sure help you stackoverflow.com/questions/17232714/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.