Database chunk() + delete()

Laravel comes with a powerful database querying library – illuminate/database. It has a lot of stuff built-in, and one of it’s handy methods is called “chunk()”.  This function has a nice purpose – it helps developers to reduce RAM usage by fetching and processing records by batch, for example:

In the example above script fetches “Advertisement” records in batches of 50 entries and processes it. It is OK when “// do stuff” does not delete entries, but if it does, we are doomed:

We won’t delete all entries using the example above, instead, entries will be processed like this:

Database chunk and delete

If you still want use delete with a batching in mind, you can use this as your base code:

Leave a Reply

Your email address will not be published. Required fields are marked *