2016-10-16 4 views
1

は、私は次のようにLaravel 5:Auth :: user()は使用するたびにデータベースにクエリを実行しますか?ユーザーの編集プロフィールページ

  1. は、ユーザーにそれが推奨私の質問ですされているなどの名前、電子メール、性別などの現在ログインしているユーザーの詳細情報の既存の値を表示したいですAuth :: user() - >名前、Auth :: user() - >メールを直接入力してフォームフィールドに入力しますか?または、私のコントローラに$user = Auth::user();のような変数を作成し、それを普通のオブジェクトのような$ userの私のビューに渡しますか?
  2. Auth :: user()を使用していますが、使用するたびに特定のビューファイルで何回もデータベースにヒットしますか?

    ありがとうございます。

答えて

4

あなたはIlluminate\AuthSessionGuard.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 (! is_null($this->user)) { 
     return $this->user; 
    } 

ので、user()を複数回呼び出すと、データベースへの複数の呼び出しをすることはありません。

1

あなたはデータベースに対して1回のリクエストしか得られないので、Auth :: user()を複数回使用することは問題ではありません。

Laravel Debugbarをアプリの最適化に最適な方法としてお勧めします。

関連する問題