1

So, first I hope my title is not misleading. Please let me know if my title fits the question.

QUESTION. I'm using Laravel 5.3 and I'm trying to find a way to add an attribute "role" to Auth::user() so that I can access it like

Auth::user()->role. 

Role is not a field in the user table used for authentication but it's a value I calculate to get. The reason I ask is I don't want to calculate role every single time I need the value, instead I want to set it when authentication succeeds then reuse it.

Any idea how I can do this?

Or is there any way I can persist a value through out the time a user is logged in so that I can calculate it once and reuse it?

2
  • Auth::user() is recreated on every request or reload , so I suggest you store your calculated role in a session , then create a middle ware which checks if the roles exists then attach the role to the Auth::user() object in that middleware ... Hope it helps Commented Apr 14, 2017 at 16:29
  • Okay so I've just read the documentation on middleware and this looks like what I'm looking for. But could tell me how to attach an extra attribute to Auth::user() or could you point me in the right direction. Is it something like "$request->user()->role = 23"? Commented Apr 14, 2017 at 16:41

2 Answers 2

4

The best way you can achieve this is in your User.php model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

    class User extends Authenticatable
    {
        use Notifiable;

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
            'name', 'email', 'password',
        ];

        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token','is_admin',
        ];

        protected function getRole(){


          if(\Session::has("role")){
            return Session::get("role");
        }else{
           //calculate and save role in session
        }

    }//end get Role

}//end class

so you will check it like this

Auth::user()->getRole();

Make sure you save the role in session after login , the getRole will get it and attach to the user() object , This doesnt need middleware too Hope it helps

Sign up to request clarification or add additional context in comments.

7 Comments

This will flush out the session variable when the user logs out, yes?
Never mind. Figured that last part out. Let me try your solution.
This returns "call to undefined method Illuminate\Database\Query\Builder::getRole()" ideas?
Thats strange.. it should work because i have a similar function but mine is isAdmin() and it works well
@VincentHokie ,no during logout you must flush out the session yourself
|
0

Just add the method of the keyword you want to use at the bottom of the model and use belongsTo() to link it up to a corresponding model. Then we just do Auth::user()->role() to use it. This is assuming you have a model called Role with a table and roles defined. (laravel 5.2+)

public function role() { 
    return $this->belongsTo( Role::class ); 
}

The entire model is here:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $guarded = ['id', 'remember_token'];

    protected $hidden = [ 'password', 'remember_token' ];

    public static $rules = array(
        'email'  => 'required|email|unique:users,email',
        'first_name' => 'required|min:2',
        'last_name'  => 'required|min:2'
    );

    public static $rules_password = array(
         'password'  => 'required|min:6|confirmed'
    );

    public function role() { 
        return $this->belongsTo( Role::class ); 
    }

}

Comments

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.