Add a new attribute in Auth::user() session in Laravel 5.3
Hi,
I wanted to add a new attribute "first_name" in my Auth::user() so I can globally access it via Auth::user()->first_name.
The first_name column is not in my users table. It's in user_details table. I tried using Auth::user()->setAttribute('first_name', $first_name); where I'm getting the first name value successfully. But the "setAttribute" isn't working.
I'm not sure if "setAttribute" still works in Laravel 5.3 but I've used it in previous versions.
Would be great if anybody could tell me how I can achieve this.
// User model
public function getFirstNameAttribute()
{
// Check if first name exists in session
if(session()->has('first_name')) {
// If so return first name
return session('first_name');
}
// If session did not have the first name
// Get the first_name from related model
$firstName = $this->userDetails->first_name;
// Save it to session
session(['first_name' => $firstName]);
// Return first name
return $firstName;
}
@ashishsanjayrao you don't have to use the session.. I just threw that in for free because you mentioned session ☺
// User model
public function getFirstNameAttribute()
{
return $this->userDetails->first_name;
}
Simply add that to your User model and of course change ->userDetails to whatever the name of your relationship is and it will be available via the Auth facade.
You can use auth()->user()->first_name or Auth::user()->firstName ..
Hi,
I've a question related. And i f I want 2 or more fields from userDetails like for example first_name and city how should I do to avoid multiple queries to the same db table?