Chunking Results — How I Implemented the Chunk Method in Laravel 4.1

The chunk method was introduced in the early stages of Laravel 5; implementing this method on my Query Builder in this project (Laravel 4.

1) won’t be possible (or will it?).

The Possibility — Implementing It The Same Old WayIt’s very simple and you’ve used it before, the do-while control structure.

This will be used to iterate over our chunked data and send a notification to each list of users.

What’s the chunk() method?This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure for processing.

chunk($count, callable $callback)Below is an example of how it’s been used on a query builder:My ResearchFrom my research, the chunk method has inbuilt counter, $page = 1 and a do-while loop.

It accepts 2 parameters, the $row_count and $callback, so after each loop using do-while it generates SQL SELECT query and passes the results to the $callback function.

An example of the generated SELECT SQL query may look like this:SELECT * FROM users LIMIT $offset, $row_countwith the $offset = 0 and $row_count = 100 , we will retrieve the first 100 rows of our data.

How to determine the $offset variable:$offset = ($page – 1) * $row_count;Doing It MyselfUsing the do-while control structure we will perform 3 iterations, selecting 100 rows at a time $row_count = 100.

The chunk method mentioned earlier will now be: chunk(100, callable $callback).

Retrieving 100 rows from row 1–100 will generate a query of:SELECT * FROM users LIMIT 0,100Retrieving 100 rows from row 101–200 will generate:SELECT * FROM users LIMIT 100,100Retrieving 100 rows from row 201–300 will generateSELECT * FROM users LIMIT 200,100The iteration will end when an empty (0) row is retrieved.

Talk Is Cheap.

Let Me Show You My CodeVoila!!!The above is evidence that there’s nothing new under the sun, and that any new framework helper can somehow be implemented for older versions.

I hope you learnt something.

Any questions and more easy ways of implementing the above are always welcome.

Happy coding legacy projects!.

. More details

Leave a Reply