• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

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

laravel 来源:Prakhar 15次浏览

在为用户编辑个人资料页,我要显示当前登录用户的详细信息,如姓名,电子邮件地址,性别等现有值我的问题如下Laravel 5:每次使用Auth :: user()都会查询数据库吗?

  1. 是它推荐给用户Auth :: user() – > name,Auth :: user() – >邮件直接填充表单字段?还是应该在我的控制器中创建一个像$user = Auth::user();这样的变量,然后像普通对象一样将它传递给我的视图以供$用户使用?
  2. 使用Auth :: user(),在给定视图文件上多次使用Auth :: user(),每次使用它时都会触发我的数据库?

    在此先感谢。

===========解决方案如下:

如果你看一下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()多次不会对数据库多次调用。


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)