【发布时间】:2015-06-16 10:52:16
【问题描述】:
在我的 Laravel 应用程序中,我在多个地方使用了 Auth::user()。我只是担心 Laravel 可能会在每次调用 Auth::user() 时进行一些查询
请多指教
【问题讨论】:
-
模型不会自动缓存。
标签: authentication laravel eloquent laravel-5
在我的 Laravel 应用程序中,我在多个地方使用了 Auth::user()。我只是担心 Laravel 可能会在每次调用 Auth::user() 时进行一些查询
请多指教
【问题讨论】:
标签: authentication laravel eloquent laravel-5
没有缓存用户模型。一起来看看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;
}
正如评论所说,第一次检索用户后,它将存储在$this->user 中,并在第二次调用时返回。
【讨论】:
对于同一个请求,如果你多次运行Auth::user(),它只会运行1次query而不是多次。
但是,如果您使用 Auth::user() 调用另一个请求,它将再次运行 1 query。
出于安全考虑,在第一次请求发出后,无法缓存所有请求。
因此,无论您调用多少次,它都会为每个请求运行 1 个查询。
我看到这里使用了一些会话来避免运行多个查询,所以你可以试试这些代码:http://laravel.usercv.com/post/16/using-session-against-authuser-in-laravel-4-and-5-cache-authuser
谢谢
【讨论】: