为什么我能够在 laravel 中使用 user() 方法,甚至无需定义它

Why Am I Able to Use user() method in laravel, without even defining it

我的 Laravel 5 来源中确实有一个 UserControllerUser 模型。 还有一个 AuthController 也存在(使用 laravel 源预构建)。

我想使用 Eloquent 模型从我的 blade 中的数据库查询数据。

但是,在我的 User 模型(Eloquent )和任何控制器中,都没有定义 user() 方法。即使那样,我也可以通过从 Auth class 访问它来在我的 blade 中使用它。为什么?

例如,

在我的 blade、{{ Auth::user()->fname }} 作品中。它从我的 users table 检索数据 fname 并回显它。

它背后的逻辑是什么,我可以为其他数据库 table 模拟相同的逻辑,例如 tasks 吗?

之所以有效,是因为 Laravel 带有体面的身份验证。

Auth 是身份验证库,有很多类似的功能,请查看 documentation!

每当你自动或手动做一些像这样的

 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 格式的令牌等数据。

然后每当你调用 {{ Auth::user()->fname }} Laravel 识别出你正在尝试获取登录用户的 fname 然后 laravel 将获取文件并获取用户的主键并从数据库中用户的 table 引用它。你可以为你拥有的所有用户 table 做这件事。

你可以了解更多here

此用户函数在

下定义
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 中定义了更多的函数,我们时不时地使用它们甚至不知道它们来自哪里