Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Discard Eloquent model changes in Laravel 9.x

In the recent Laravel 9.x release, the framework introduced a new discardChanges() method on the Model class. This method allows you to discard the changes made to the model instance. So, let’s see how we can use this method.

The discardChanges() method

The discardChanges() method is a new method introduced in Laravel 9.x. It allows you to discard the changes made to the model instance. So, if you have made some changes to the model instance and you want to discard those changes, you can use this method.

Here’s how you can use this method.

$user = User::create([
    'name' => 'John Doe',
]);

$user->discardChanges();

echo $user->name;
// null

As you can tell, the discardChanges() method will discard any unsaved changes, and return the model to its original state, without performing a database call.

discardChanges() vs refresh()

This is different from the refresh() method which will refresh the model instance from the database.

So, if you want to discard the changes made to the model instance and refresh it from the database, you can use the refresh() method like so.

$user = User::where([
    'name' => 'John Doe',
]);

$user->name = 'Jane Doe';

$user->refresh();

echo $user->name;
// John Doe

Rodrigo Pedra Brum nicely explains it in this PR comment.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), 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-digest 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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?