7

If a user logs in Laravel 5.1 we can access user id

Auth::user()->id

In my previous app (not laravel) when a user logs in I'm registering a session for userid. And I was checking $_SESSION['user_id'] is available or not.

I want to ask that when i call Auth::user()->id is it generates and sql query for every request ? If it does it is not good for performance.

Should I register a new session like

Session::put('user_id', Auth::user()->id);

for performance.

Or Auth:user()->id is best choice ?

2 Answers 2

17

You can use Auth::id() instead. This grabs it from the session. If one doesn't exist in the session, then it will run the query and grab it from the database.

3
  • Does Laravel register session for user id when logging in? Nov 2, 2015 at 21:12
  • Yes it does. When you login, it fires this line of code $this->updateSession($user->getAuthIdentifier());.
    – Thomas Kim
    Nov 2, 2015 at 21:23
  • 1
    this is not true, it always does the query
    – user151496
    Oct 19, 2022 at 8:18
4

This is not an actual answer, but it intends to show how Auth::id() works. Add the following route to your web.php:

Route::get('/fake', function () {
  \DB::enableQueryLog();
  Auth::id();
  dump(\DB::getQueryLog());
});

Now, navigate to /fake, which results in the something like:

array:1 [▼
  0 => array:3 [▼
    "query" => "select * from `users` where `id` = ? limit 1"
    "bindings" => array:1 [▼
      0 => 284
    ]
    "time" => 15.37
  ]
]

I tried this over and over, and it seems that Auth::id() always queries the database, as opposed to somehow caching the result in the session (I'm using Laravel 5.6, PHP 7.2.3, and MariaDB 10.2.14).

To confirm, I also enabled MariaDB logging feature, and I got:

180611 12:08:10    77 Connect   user@localhost as anonymous on dbname
           77 Query use `dbname`
           77 Prepare   set names 'utf8mb4' collate 'utf8mb4_unicode_ci'
           77 Execute   set names 'utf8mb4' collate 'utf8mb4_unicode_ci'
           77 Close stmt    
           77 Prepare   set time_zone="+04:30"
           77 Execute   set time_zone="+04:30"
           77 Close stmt    
           77 Prepare   set session sql_mode='NO_ENGINE_SUBSTITUTION'
           77 Execute   set session sql_mode='NO_ENGINE_SUBSTITUTION'
           77 Close stmt    
           77 Prepare   select * from `users` where `id` = ? limit 1
           77 Execute   select * from `users` where `id` = 284 limit 1
           77 Close stmt    
           77 Quit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.