Getting Auth User ID in Laravel

26,480

Solution 1

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.

Solution 2

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
Share:
26,480
Cihan Küsmez
Author by

Cihan Küsmez

Updated on June 11, 2020

Comments

  • Cihan Küsmez
    Cihan Küsmez almost 4 years

    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 ?