1

私の Laravel 5 ソースにはUserControllerand Model があります。Userまた、AuthControllerPresent も 1 つあります (laravel ソースでビルド済みで出荷されます)。

Eloquent モデルを使用して、ブレードで db からデータをクエリしたいと思います。

ただし、私のUserモデル(Eloquent)でもコントローラーでも、user()メソッドは定義されていません。それでも、Authクラスからアクセスすることでブレードで使用できました。なぜ?

例えば、

私のブレードでは、{{ Auth::user()->fname }}動作します。fnameテーブルからデータを取得してusersエコーします。

その背後にあるロジックは何tasksですか?

4

3 に答える 3

1

このユーザー関数は以下で定義されています

vendor/laravel/framework/src/Illuminate/Auth/Guard.php

次の内容で:

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

    // If we have already retrieved the user for the current request we can just
    // return it back immediately. We do not want to pull the user data every
    // request into the method because that would tremendously slow an app.
    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))
    {
        $user = $this->provider->retrieveById($id);
    }

    // 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;
}

この Guard.php には、より多くの関数が定義されており、それらがどこから来ているのかさえ知らずに、時々使用しています。

于 2015-06-04T06:52:54.007 に答える
1

自動または手動で行うときはいつでも、このようなものがあります

 if (Auth::attempt(['email' => $email, 'password' => $password])) 
{
}

選択したユーザーのデータは、storage/framework/sessions

次のようなデータがあります

a:4:{s:6:"_token";s:40:"PEKGoLhoXMl1rUDNNq2besE1iSTtSKylFFIhuoZu";s:9:"_previous";a:1:{s:3:"url";s:43:"http://localhost/Learnings/laravel5/laravel";}s:9:"_sf2_meta";a:3:{s:1:"u";i:1432617607;s:1:"c";i:1432617607;s:1:"l";s:1:"0";}s:5:"flash";a:2:{s:3:"old";a:0:{}s:3:"new";a:0:{}}}

上記のセッション ファイルにはデータがなく、ユーザーの ID、URL、トークンなどのデータが json 形式で含まれます。

次に、Laravelを呼び出すたびに{{ Auth::user()->fname }}、ログインしているユーザーをフェッチしようとしていることを認識しfname、laravelはファイルをフェッチしてユーザーの主キーを取得し、データベースのユーザーのテーブルから参照します。あなたが持っているユーザーのすべての列に対してそれを行うことができますtable

詳しくはこちら

于 2015-06-04T06:48:06.033 に答える