每次调用Auth :: user()时,Laravel都会查询数据库吗?

Eme*_*bah 3 authentication laravel eloquent laravel-5

在我的Laravel应用程序中,我Auth::user()在多个地方使用过.我只是担心Laravel可能会对每次调用进行一些查询Auth::user()

好心劝告

luk*_*ter 12

没有缓存用户模型.我们来看看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;
    }
Run Code Online (Sandbox Code Playgroud)

正如评论所说,在第一次检索用户之后,它将被存储$this->user并在第二次呼叫时返回.

  • 请注意,这在不同请求之间不是持久的.我的意思是每次有新请求(例如:用户刷新页面)时,无论内部缓存如何,驱动程序每次都会进入数据库. (2认同)

Joh*_*rgo 5

对于同一个请求,如果你Auth::user()多次运行,它只会运行 1 次query而不是多次。但是,如果您使用 调用另一个请求Auth::user(),它将query再次运行 1 。

出于安全角度的考虑,在发出第一个请求后,无法为所有请求缓存。

因此,无论您调用多少次,它都会为每个请求运行 1 个查询。

我在这里看到使用一些会话来避免运行多个查询,因此您可以尝试这些代码:http : //laravel.usercv.com/post/16/using-session-against-authuser-in-laravel-4-and- 5-cache-authuser

谢谢