gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:41:22 26 4
gpt4 key购买 nike

在用户的编辑个人资料页面上,我想显示当前登录用户详细信息的现有值,例如姓名、电子邮件、性别等。我的问题如下

  1. 是否建议用户直接使用 Auth::user()->name 、 Auth::user()->email 来填充表单字段?或者我应该在 Controller 中创建一个像 $user = Auth::user(); 这样的变量,并将其像常规对象一样传递到我的 View 中 $user 吗?

  2. 每次使用给定 View 文件时多次使用 Auth::user() 是否都会访问我的数据库?

    提前致谢。

最佳答案

如果您查看 Illuminate\Auth 中的 SessionGuard.php 文件,您将看到使用的方法 user()检索当前经过身份验证的用户:

/**
* Get the currently authenticated user.
*
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function user()
{
if ($this->loggedOut) {
return;
}

// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}

$id = $this->session->get($this->getName());

// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;

if (! is_null($id)) {
if ($user = $this->provider->retrieveById($id)) {
$this->fireAuthenticatedEvent($user);
}
}

// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->getRecaller();

if (is_null($user) && ! is_null($recaller)) {
$user = $this->getUserByRecaller($recaller);

if ($user) {
$this->updateSession($user->getAuthIdentifier());

$this->fireLoginEvent($user, true);
}
}

return $this->user = $user;
}

// If we've already retrieved the user for the current request we can just return it back immediately. We do not want to fetch the user data on every call to this method because that would be tremendously slow.

    if (! is_null($this->user)) {
return $this->user;
}

因此,多次调用 user() 不会多次调用数据库。

关于Laravel 5:Auth::user() 每次使用时都会查询数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40065504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com