Playing
03. Batch updating

Transcript

00:00
The next thing and probably much more useful than the visuals is batch updating or bulk updating. So how would we normally do this within Laravel? Let's take a look at the way that we can't do
00:11
this first of all. So let's go ahead and use post here and let's just say that we wanted to go ahead and update all posts to update their title. Let's go ahead and pass in a new title here and just say a new title and you can see that my editor is telling me that this method doesn't actually exist. If we come over and give this a refresh you can see the update cannot be called
00:30
statically. So the way that we would get around bulk updating and not having to use the model itself would be to use the db facade. So we would go ahead and use the db facade here which we'll just pull in very quickly. We'd reference the table name and then we would go ahead and call update on this passing through the data that we wanted to update. So a new title you can see that
00:53
from before of course this didn't actually update. So let's go over and just give this a refresh and if we head back over to the database there we go both of them records have been updated in one query with that new title. Now doing this always makes me feel a little bit more uncomfortable so it's not the end of the world because database tables don't change names that often but I much
01:15
prefer to do this at the actual model level much like this. How do we do that? Well very very simple we just use the query builder method to pull back a builder before we call update on it. So let's pull this line down here and let's go ahead and say query and update. There we go. So let's go another new title and let's go back over and give that a refresh and there we go. So that's
01:41
been updated and I much prefer this way because we are referencing the model directly itself which means if the database does change or if we have anything else in that model that triggers when we do an update then that will work nicely. A word of warning though this will still not fire eloquent events when you do a bulk update on anything within Laravel it will never fire
02:03
events for that model so you can't use this with model events without any kind of tweaking but this is more of a visual change just so you can see a little bit clearer what we're updating rather than using the db facade pulling that in and referencing the table itself. So there we go the query method is useful for batch updating.
7 episodes 23 mins

Overview

Ever used the Eloquent query() method in Laravel before? In this short course, we'll dive into what this method does, and demonstrate the ways it can be used.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!

Episode discussion

No comments, yet. Be the first!