2016-10-16 112 views
1

在爲用戶編輯個人資料頁,我要顯示當前登錄用戶的詳細信息,如姓名,電子郵件地址,性別等現有值我的問題如下Laravel 5:每次使用Auth :: user()都會查詢數據庫嗎?

  1. 是它推薦給用戶Auth :: user() - > name,Auth :: user() - >郵件直接填充表單字段?還是應該在我的控制器中創建一個像$user = Auth::user();這樣的變量,然後像普通對象一樣將它傳遞給我的視圖以供$用戶使用?
  2. 使用Auth :: user(),在給定視圖文件上多次使用Auth :: user(),每次使用它時都會觸發我的數據庫?

    在此先感謝。

回答

4

如果你看一下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()多次不會對數據庫多次調用。

1

你只會得到1個數據庫請求,所以多次使用Auth :: user()不是問題。

我建議您使用Laravel Debugbar作爲應用程序優化的最舒適的方式。

相關問題