Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Reverting back to the original model instance in Laravel

January 16, 2022 ·

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.

The refresh() method

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.

The fresh() method

The 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"
Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?