Does PHP Laravel 4 use a database every time the Auth class is called?

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

It seems to me that I need to often call such things in most of my models and controllers ...

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

So my question is that you call this several times in the application, several times get into the database, or is it enough to cache it somewhere for the rest of the request / page assembly?

Or do I need to do it differently? I looked at the Auth class, but did not manage to check each file (16 files for Auth)

+4
source share
2 answers

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

 // 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; } 

It seems to me that he will receive the user from the database only once per request. That way you can call him as many times as you want. It will only hit DB.

+9
source

Auth::user() only hits the database once, so the problem does not cause many times. By the way, you can cache useful information about the user you want to access often.

+1
source

Source: https://habr.com/ru/post/1499864/


All Articles