Home » Php » Does PHP's Laravel 4 hit the Database on every call to the Auth class?

Does PHP's Laravel 4 hit the Database on every call to the Auth class?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am building my first Laravel 4 Application (PHP).

I find myself needing to call somthing like this often in most of my Models and Controllers…

$this->user = Auth::user();

So my question is, is calling this several times in the application, hitting the Database several times, or is it smart enough to cache it somewhere for the remainder of the request/page build?

Or do I need to do it differently myself? I glanced over the Auth class but didnt have time to inspect every file (16 files for Auth)

Answers:

Here is the code for the method Auth::user().

// vendor/laravel/framework/src/Illuminate/Auth/Guard.php

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

    // If we have already retrieved the user for the current request we can just
    // return it back immediately. We do not want to pull the user data every
    // request into the method becaue that would tremendously slow the app.
    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) and ! is_null($recaller))
    {
        $user = $this->provider->retrieveByID($recaller);
    }

    return $this->user = $user;
}

To me, it looks like it will get the user from the database only once per request. So, you can call it as many times as you want. It will only hit the DB once.

Questions:
Answers:

Auth::user() only hits the DB once, so it’s not a problem invokes it many times. Btw, you can cache useful information of the user that you want to access frequently.