In this episode, we dive into batch updating (or bulk updating) records in Laravel, which is super useful when you want to update a lot of rows at once. We first take a look at how you can't do it directly with the model's update
method, which you'll quickly find out throws an error if you try to call it statically on the model.
Next, we try out the DB
facade approach, where you specify the table name and update fields using the query builder. This works just fine, and when we refresh the database, all the records reflect the new changes.
However, it doesn't feel as nice because you're hardcoding the table name, and it doesn't feel as "Eloquent". So, we move over to the proper model-centric way: we use the model's query()
method, chain on update()
, and see that updates work just as expected. This feels much cleaner and keeps everything in sync with your app's structure—plus, if your table name ever changes, your code is safer.
But, here's an important heads up: bulk updates using these methods will not fire Eloquent model events (like updating
or updated
). So if you rely on model events, you'll need to handle that separately!
All in all, we show both approaches, explain why you might use one over the other, and encourage best practices for batch updating in Laravel.