What’s the real difference and when to use Chunk() and chunkById() from the Laravel

Asked

Viewed 387 times

0

It wasn’t very clear to me how the documentation works and I couldn’t find any content to fully explain how to use chunkById() and the difference practices for Chunk();

How do I return the result of chunkById() to the view? How do I paginate these records in the view? The way below doesn’t work...

DB::table('fornecedores')->orderBy('razao')->chunkById(100, function($fornecedores){
            foreach ($fornecedores as $fornecedor) {
                DB::table('fornecedores')
                    ->where('id', $fornecedor->id);
            }

1 answer

0

The difference between the two is how pure SQL is mounted, the chunkById uses the id and limit when mounting sql, while the chunk uses limit and offset for example:

Using chunkById

select * from `fornecedores` where `id` > ? order by `razao` asc limit 10

Using Chunk

select * from `fornecedores` order by `razao` asc limit 10 offset 0

Chunk is not for paging, he is for you to process blocks of data that would normally be too heavy in cpu or memory to be done all together.

To paginate a query exists the paginate

public function index()
{
    $fornecedores = DB::table('fornecedores')->orderBy('razao')->paginate(10);

    return view('fornecedores.index', ['fornecedores' => $fornecedores]);
}

Then to display the data in the view is like this:

<div class="container">
    @foreach ($fornecedores as $fornecedore)
        {{ $fornecedore->id }}
    @endforeach
</div>

{{ $fornecedores->links() }}

I recommend reading the documentation here.

  • I know the paginate, but for example, I have 100,000 suppliers in my bank, I want to limit to improve performance. If I limit to 1000 using Chunk, I can’t page that 1000? or Chunk doesn’t serve to return data for view listing?

  • @user143874 depends, you want to page only the 1000 record or the 100 thousand?

  • @user143874 Would you use simplePaginate to be more efficient, but would only have the next and Previous button, another thing that can be done to greatly improve the performance is to put in the query the columns you need, for example if the vendors table has 50 Columns and you only use the id and name in the listing, the query you used will return the 50 and not only the 2 Columns used in the view.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.