Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Get all the changes applied by model updates in Laravel

Here’s a little tip I get to know about Eloquent through this tweet by ninjaparade.

So, oftentimes, it would be useful if you want to have all the changes applied by the model update operation. Probably in situations when you want to show the user which all the things have been affected once they update something.

Turns out, we can get these changes by using the getChanges() method on the model instance. Take the following for example.

$book = Book::find(1);

$book->update([
    'title' => 'Maharani'
    'author' => 'Ruskin Bond'
]);

Now, if we want to know which all fields have been affected by the update, we can call the getChanges() method like so.

$book->getChanges();

/*
[
    'title' => 'Maharani',
    'author' => 'Ruskin Bond',
    'updated_at' => '2021-07-20 00:08:25'
]
*/

As you can tell, we can get the fields that are updated including the updated_at field.

Pretty handy I must say!

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