Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ashishsanjayrao's avatar

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.

Thanks!

0 likes
7 replies
SaeedPrez's avatar

Hi @ashishsanjayrao,

You can use an accessor, something like 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;
}

Edited some nasty bugs

ashishsanjayrao's avatar

So I HAVE to use Sessions instead of adding a new attribute to the Auth facade right? There's no way I can add an attribute?

SaeedPrez's avatar
Level 50

@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 ..

lightframes's avatar

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?

Please or to participate in this conversation.