5

In my Laravel application I used Auth::user() in multiple places. I am just worried that Laravel might be doing some queries on each call of Auth::user()

Kindly advice

Emeka Mbah
  • 16,745
  • 10
  • 77
  • 96

2 Answers2

17

No the user model is cached. Let's take a look at Illuminate\Auth\Guard@user:

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 because that would tremendously slow an app.
    if ( ! is_null($this->user))
    {
        return $this->user;
    }

As the comment says, after retrieving the user for the first time, it will be stored in $this->user and just returned back on the second call.

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • 5
    Please note that this is not persistent between different requests. What I mean is that each time there is a new request (e.g: User refreshes the page), regardless of the inner caching, the driver goes to database every time. – Arda Sep 02 '15 at 20:04
5

For same Request, If you run Auth::user() multiple time, it will only run 1 query and not multiple time. But , if you go and call for another request with Auth::user() , it will go and run 1 query again.

This cannot be cached for all request after first request has been made due to security point of view.

So, It runs 1 query per request irrespective of number of time you are calling.

I see use of some session here to avoid run multiple query, so you can try these code : http://laravel.usercv.com/post/16/using-session-against-authuser-in-laravel-4-and-5-cache-authuser

Thanks

John Cargo
  • 1,839
  • 2
  • 29
  • 59
  • 1
    Caching between requests will be important when the user is not in a local database, but at the end of an API that may take some time to fetch. – Jason Jun 11 '18 at 11:12