7

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 3

16

It is very simple. You can create an Accessor for that.

App\User.php

public function getCustomAttribute()
{
    return 'Custom attribute';
}

Now, you can access it anywhere using:

echo Auth::user()->custom;

More info:

https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor

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

Comments

4

Add custom to your User model $appends array.

protected $appends = [ 'custom' ];

2 Comments

Thanks! That's exactly what I needed to make the extra field available on the frontend.
How did I miss this? I had it already on my code! Thanks. Link to docs: laravel.com/docs/6.x/…
0

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();

Comments

Your Answer

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