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