【问题标题】:Getting Auth User ID in Laravel在 Laravel 中获取身份验证用户 ID
【发布时间】:2016-02-02 21:08:02
【问题描述】:

如果用户登录 Laravel 5.1,我们可以访问用户 ID

Auth::user()->id

在我以前的应用程序(不是 laravel)中,当用户登录时,我正在为用户 ID 注册会话。我正在检查 $_SESSION['user_id'] 是否可用。

我想问一下,当我调用Auth::user()->id 时,它会为每个请求生成和 sql 查询吗?如果是这样,则对性能不利。

我应该像

这样注册一个新会话吗?
Session::put('user_id', Auth::user()->id);

为了性能。

或者 Auth:user()->id 是最好的选择?

【问题讨论】:

    标签: php session laravel


    【解决方案1】:

    您可以改用Auth::id()。这从会话中获取。如果会话中不存在,那么它将运行查询并从数据库中获取它。

    【讨论】:

    • Laravel 登录时是否为用户 id 注册会话?
    • 是的。当你登录时,它会触发这行代码$this->updateSession($user->getAuthIdentifier());
    【解决方案2】:

    这不是一个实际的答案,但它旨在展示Auth::id() 的工作原理。将以下路由添加到您的web.php

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

    现在,导航到/fake,结果如下:

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

    我一遍又一遍地尝试这个,似乎Auth::id() 总是查询数据库,而不是以某种方式在会话中缓存结果(我使用的是 Laravel 5.6、PHP 7.2.3 和 MariaDB 10.2.14 )。

    为了确认,我还启用了MariaDB logging feature,我得到了:

    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
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2017-05-19
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      • 2019-10-10
      • 2018-11-26
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多