Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Get all the changes applied by model updates in Laravel

July 20, 2021 ·

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 (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?