Home > OS >  What is the difference between chunk and pagination in Laravel?
What is the difference between chunk and pagination in Laravel?

Time:06-15

I already read some article but I am still confused. I n pagination it will execute a query when load a page but what happen in chunk ? I read https://laravel-school.com/posts/laravel-pagination-vs-chunk-51 this article and so on.

CodePudding user response:

Now pagination works on a per page basis. So if you for example have 100 records and you retrieve 10 records per page you need to perform 10 queries to get all results. However since it's pagination you have a page number you use to determine which records you will return. For example page 3 will return the records 21-30 and so on. Here you will always only load 10 records in memory and return them. Query wise this works with a limit and offset to determine the correct records.

Now looking at chunk it's actually a bit different. So if we still take the 100 records and we chunk them by 10 records we still parse all the 100 records. However it will only load 10 records in memory at a time. So it's using a similar query approach using limit and offset, however it will eventually return all results, but in batches/chunks instead of only return 1 set of records.

The documentation also does a good job of explaining this: https://laravel.com/docs/9.x/eloquent#chunking-results

  • Related