Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "Refresh" the User object in Laravel?

In Laravel you can do this:

$user = Auth::user();

Problem is, if I do changes on items on that object, it will give me what was there before my changes. How do I refresh the object to get the latest values? I.e. To force it to get the latest values from the DB?

like image 305
coderama Avatar asked Feb 13 '14 10:02

coderama


2 Answers

You can update the cache object like this.

Auth::setUser($user);

for Example

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

Auth::setUser($user);

log::error(Auth::user()->name)); // Will be 'NEW Name'
like image 65
Er. Mohit Agrawal Avatar answered Nov 05 '22 04:11

Er. Mohit Agrawal


[This answer is more appropriate for newer versions of Laravel (namely Laravel 5)]

On the first call of Auth::user(), it will fetch the results from the database and store it in a variable.

But on subsequent calls it will fetch the results from the variable.

This is seen from the following code in the 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;
    }
    ...
}

Now if we make changes on the model, the changes will automatically be reflected on the object. It will NOT contain the old values. Therefore there is usually no need to re-fetch the data from the database.

However, there are certain rare circumstances where re-fetching the data from the database would be useful (e.g. making sure the database applies it's default values, or if changes have been made to the model by another request). To do this run the fresh() method like so:

Auth::user()->fresh()
like image 11
Yahya Uddin Avatar answered Nov 05 '22 04:11

Yahya Uddin