如何在Laravel中“刷新”User对象?

问题描述 投票:14回答:5

在Laravel你可以这样做:

$user = Auth::user();

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

laravel laravel-4
5个回答
2
投票

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

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

如果它不能正常工作,你的代码中还有其他东西,我们在这里没有看到,为你缓存该用户。


16
投票

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

Auth::setUser($user);

例如

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

Auth::setUser($user);

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

5
投票

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

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

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

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

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


5
投票

[这个答案更适合新版本的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;
    }
    ...
}

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

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

Auth::user()->fresh()

2
投票

派对有点晚了,但这对我有用:

Auth::user()->update(array('name' => 'NewName'));
© www.soinside.com 2019 - 2024. All rights reserved.