How to add custom value to Auth::user() in Laravel

Viewed 14040

I've some custom value that I want to use in the whole project when the user logs in. I am writing a function in controllers but calling that static method every time can make code little bit lengthy. Instead of calling the function I want to assign a custom value to Auth::user() so I can use it anywhere in the project. I tried it below code but it won't work

public static function getUserDetailById($id){
      //Do Something  and assign value to $custom_val
      Auth::user()->custom = $custom_val;
}

But It's not working in any controller or view. I tried to check custom value in Auth::user() but it's missing.

Is there any way to add custom value to Auth::user() without adding new column in a table?

3 Answers

You can define a function & accessor on the user model to get different data as per logic-

// This method will help you to get complete table data as per need
public function xyz() 
{
    return XyzModel::where('user_id', $this['id'])->first();
}

// Accessor
public function getXyzIdAttribute()
{
     return $this->xyz()->id ?? null;
}

Now you can get custom data as well as complete data set of an XYZ Model.

Auth::user()->xyz_id; // return the id of xyz_model via accessor

Auth::user()->xyz();
Related