我确实有一个UserController
和User
模型在我的Laravel 5源。还有一个AuthController
也存在(与laravel源代码一起预构建)。
我想在我的刀片中使用Eloquent Models从db查询数据。
然而,无论是在我的User
模型(Eloquent)中还是在任何控制器中,都没有定义user()
方法。即使这样,我也可以通过Auth
类访问它来使用它。为什么?
例如
在我的刀片,{{ Auth::user()->fname }}
工作。它从我的users
表中检索数据fname
并回显它。
它背后的逻辑是什么,我可以模仿其他db表,如tasks
吗?
无论你是自动还是手动操作
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:{}}}
上面的会话文件没有任何数据,它将有json格式的用户id, url, token等数据。
然后,每当你调用{{ Auth::user()->fname }}
Laravel认识到你正在试图获取登录用户的fname
,然后Laravel将获取文件,并获得用户的主键,并从用户的表从数据库中引用它。你可以对用户table
的所有列都这样做。
您可以在这里了解更多信息
这个用户函数定义在
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;
}
this guard。php中定义了更多函数,我们甚至不知道它们是从哪里来的
这是因为Laravel具有良好的身份验证。
Auth是身份验证库,有很多这样的特性,请查看文档!