12

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

  1. 是否推荐用户 Auth::user()->name , Auth::user()->email 直接填充表单字段?或者我应该$user = Auth::user();在我的控制器中创建一个变量,然后像普通对象一样将它传递给我的视图到 $user?

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

    提前致谢。

4

2 回答 2

14

如果您查看 中的SessionGuard.php文件Illuminate\Auth,您将看到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 (! is_null($this->user)) {
        return $this->user;
    }

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

于 2016-10-16T02:46:22.063 回答
2

您只会收到 1 个对数据库的请求,因此多次使用 Auth::user() 不是问题。

我推荐你使用Laravel Debugbar作为应用程序优化最舒适的方式。

于 2016-10-16T00:25:17.790 回答