Reverting back to the original model instance in Laravel
In Laravel, when you want to update the model that already exists in the database, you would first retrieve that model, set any attributes you wish to update, and then call the model’s
save method like so.
use App\Models\Book; $book = Book::find(1); $book->name = 'Maharani'; $book->author = 'Ruskin Bond'; $book->save();
Sometimes, though, it might be the case when you have a model instance, you have set some of the model attributes and for some reason, you want to discard all that has been set on the model and just revert back to the original model instance.
Well, it’s pretty easy with Laravel Eloquent.
Laravel comes with a
refresh() method, which when called on the model instance, will discard all the model attributes update and re-hydrate the existing model using fresh data from the database like so.
$book = Book::where('name', 'Maharani')->first(); $book->name = 'Room on the Roof'; $book->refresh(); $book->name; // "Maharani"
Note that, The
refresh() method will “refresh” all of the model’s loaded relationships as well.
refresh() method would refresh the model instance on which it has been called. But if you want the model intact and create a fresh new model instance instead, you can use the
refresh() method like so.
$book = Book::where('name', 'Maharani')->first(); $book->name = 'Room on the Roof'; $newBook = $book->fresh(); $book->name // "Room on the Roof" $newBook->name; // "Maharani"