如何在Laravel中"刷新"User对象?

cod*_*ama 17 laravel laravel-4

在Laravel你可以这样做:

$user = Auth::user();
Run Code Online (Sandbox Code Playgroud)

问题是,如果我对该对象上的项目进行了更改,它将为我提供更改之前的内容.如何刷新对象以获取最新值?即强制它从数据库中获取最新值?

Er.*_*wal 19

您可以像这样更新缓存对象.

Auth::setUser($user);
Run Code Online (Sandbox Code Playgroud)

例如

$user = User::find(Auth::user()->id);
$user->name = 'New Name';
$user->save();

Auth::setUser($user);

log::error(Auth::user()->name)); // Will be 'NEW Name'
Run Code Online (Sandbox Code Playgroud)


Yah*_*din 9

[这个答案更适合新版本的Laravel(即Laravel 5)]

在第一次调用时Auth::user(),它将从数据库中获取结果并将其存储在变量中.

但是在后续调用中,它将从变量中获取结果.

这可以从framemwork中的以下代码中看出:

public function user()
{
    ...
    // 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;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我们对模型进行更改,更改将自动反映在对象上.它不包含旧值.因此,通常无需从数据库中重新获取数据.

但是,在某些罕见的情况下,从数据库中重新获取数据会很有用(例如,确保数据库应用它的默认值,或者如果另一个请求对模型进行了更改).为此,运行如下fresh()方法:

Auth::user()->fresh()
Run Code Online (Sandbox Code Playgroud)


Jon*_*Jon 6

Laravel会为您做到这一点,但是,在同一请求期间,您不会看到Auth :: user()中反映的更新.来自/Illuminate/Auth/Guard.php(位于安东尼奥在答案中提到的代码上方):

// 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;
}
Run Code Online (Sandbox Code Playgroud)

因此,如果您尝试将用户名从"旧名称"更改为"新名称":

$user = User::find(Auth::user()->id);
$user->name = 'New Name';
$user->save();
Run Code Online (Sandbox Code Playgroud)

后来在同一个请求中,您尝试通过检查来获取名称Auth::user()->name,它将为您提供"旧名称"

log::error(Auth::user()->name)); // Will be 'Old Name'


Ant*_*iro 1

Laravel 已经为你做到了。每次你这样做Auth::user(),Laravel 都会这样做

// 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);
}
Run Code Online (Sandbox Code Playgroud)

它将当前用户清空,如果已记录,则使用存储在会话中的记录 ID 再次检索它。

如果它没有按预期工作,则说明您的代码中有其他内容(我们在这里没有看到),为您缓存该用户。

  • 这是不准确的(至少从 4.2 开始)。在上面 $user 设置为 null 的地方,Auth 检查 $this->user 是否已设置并使用它。它不会从数据库刷新。请参阅https://github.com/laravel/framework/blob/4.2/src/Illuminate/Auth/Guard.php#L130 (2认同)