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

itechsystemsolutions's avatar

Auth::user()

How does Auth::user() persists from page to page? Does it use session or what? I'm just curious. Thanks.

0 likes
8 replies
veve286's avatar

@greenroofcorp Yes it uses session .

But keep in mind that all of the laravel session is based on Symfony Session driver

it is not the same as PHP default session.

itechsystemsolutions's avatar

@veve286 Okay. I'm just wondering because sometimes when I reload the page, all the sessions that I declared using the session() function gets erased but the Auth::user() is still there. Any idea why this happens?

jekinney's avatar

Are you flashing to session, or using put?

jekinney's avatar

For 5.3 docs say Session::put() or session([key => value]);

https://laravel.com/docs/5.0/session#configuration

Also make sure your driver is set correctly. Auth facade handles sessions on its own functions (cookie too) so if your session isn't persisting it'll show a query to reset the Auth facade back up. Check for that to.

bhupendra's avatar

Auth::user() is a singleton and that's why it is available throughout the application! Only first call of Auth:user() will hit the database.

bhupendra's avatar

@greenroofcorp no such lession in Laracast.

It looks like to me that It will only hit the DB once.

/**
 * Get the currently authenticated user.
 *
 * @return \Illuminate\Contracts\Auth\Authenticatable|null
 */
public function user()
{
    if ($this->loggedOut) {
        return;
    }

    // If we've already retrieved the user for the current request we can just
    // return it back immediately. We do not want to fetch the user data on
    // every call to this method because that would be tremendously slow.
    if (! is_null($this->user)) {
        return $this->user;
    }

    $id = $this->session->get($this->getName());

    // First we will try to load the user using the identifier in the session if
    // one exists. Otherwise we will check for a "remember me" cookie in this
    // request, and if one exists, attempt to retrieve the user using that.
    $user = null;

    if (! is_null($id)) {
        $user = $this->provider->retrieveById($id);
    }

    // If the user is null, but we decrypt a "recaller" cookie we can attempt to
    // pull the user data on that cookie which serves as a remember cookie on
    // the application. Once we have a user we can return it to the caller.
    $recaller = $this->getRecaller();

    if (is_null($user) && ! is_null($recaller)) {
        $user = $this->getUserByRecaller($recaller);

        if ($user) {
            $this->updateSession($user->getAuthIdentifier());

            $this->fireLoginEvent($user, true);
        }
    }

    return $this->user = $user;
}

Please or to participate in this conversation.