Skip to content
Advertisement

How to reload/refresh model from database in Laravel?

In some of my tests, I have a user model I have created and I run some methods that need to save certain attributes. In rails, I would typically call something like user.reload which would repopulate the attributes from the database.

Is there a way in laravel to do that? I read through the api and couldn’t find a method for it: http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Model.html Any ideas on the “right” way to do this?

Advertisement

Answer

I can’t see it either. Looks like you’ll have to:

$model = $model->find($model->id);

You can also create one yourself:

public function reload()
{
    $instance = new static;

    $instance = $instance->newQuery()->find($this->{$this->primaryKey});

    $this->attributes = $instance->attributes;

    $this->original = $instance->original;
}

Just tested it here and it looks it works, not sure how far this goes, though, Eloquen is a pretty big class.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement