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
Pretty handy I must say!
👋 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!