Posted inphp / Laravel

Laravel Chunk Method Using Eloquent Example

Today, We want to share with you laravel chunk.In this post we will show you laravel order by desc, hear for firstorfail laravel we will give you demo and example for implement.In this post, we will learn about Pluck In Laravel with an example.

Laravel Chunk Eloquent Method Example

The chunk() method is use to split the collection into multiple smaller collection. Its useful into the pagination and listing of items.

$patients = Patient::all();
$charge = $patients->chunk(4);

What is Chunks?

Chunks an array into arrays with length elements.

Laravel comes up with an excellent Eloquent ORM. Chunking the array or collection is the best way to process large data in PHP.

array_chunk ( array $array , int $length , bool $preserve_keys = false ) : array.

pagination to your query like so:

$data = Inspector::latest('id')
    ->select('id', 'pcode', 'status', 'desc', 'price')
    ->where('pcode', 'LIKE', '%' . $searchtext . '%')
    ->paginate();

Process big DB table with chunk() method

$products = Product::all();
foreach ($products as $product) {
  $data_results = ($product->some_field > 0) ? 1 : 0;
  // might be more logic here
  $product->update(['db_clm_key' => $data_results]);
}
Product::chunk(100, function ($products) {
  foreach ($products as $product) {
    $data_results = ($product->some_field > 0) ? 1 : 0;
    // might be more logic here
    $product->update(['db_clm_key' => $data_results]);
  }
});

Use laravel chunk with Eloquent Model

laravel controller

$products = Product::all(); // Fetch some data

Laravel View:

@foreach($products->chunk(3) as $row)
    
@foreach($row as $product)
{{ $product->name}}
@endforeach
@endforeach

all types of laravel collections

$players = collect(['bhavik', 'amit', 'vivek', 'bharti', 'sejal', 'dimple']);
$chunks = $players->chunk(3);
 
print_r($chunks);
 
/*
Output:
 
Array
(
    [0] => Array
        (
            [0] => bhavik
            [1] => amit
            [2] => vivek
        )
 
    [1] => Array
        (
            [3] => bharti
            [4] => sejal
            [5] => dimple
        )
 
)
*/

Insert big data on the laravel

items array to collection:

$items = collect($items);

Make chunk

$chunks = $items->chunk(100);

foreach and insert by 100 each time

foreach($chunks as $chunk){
    DB::table('items')->insert($chunk->toArray());
}

how to return chunk data laravel?

$count = 0;
DB::table('products')->chunk(200, function($products) use (&$count)
{
    Log::debug(count($products)); // will log the current iterations count
    $count = $count + count($products); // will write the total count to our method var
});
Log::debug($count); // will log the total count of records

laravel chunk select

DB::table('products')->chunk(100, function($products)
{
    foreach ($products as $product)
    {
        //
    }
});

get data from model in chunks laravel

$data = Inspector::latest('id')
    ->select('id', 'pcode', 'status', 'desc', 'price')
    ->where('pcode', 'LIKE', '%' . $searchtext . '%')
    ->chunk(50, function($inspectors) {
        foreach ($inspectors as $inspector) {
            // apply some action to the chunked results here
        }
    });

In Laravel, the chunk() method using Eloquent is used to process large datasets from a database table in smaller “chunks”, or batches, rather than retrieving all the records at once. This can be helpful to reduce memory usage and improve the performance of your application.

Here is an example of how to use the chunk() method with Eloquent in Laravel:

DB::table('my_table')->orderBy('id')->chunk(100, function ($records) {
    foreach ($records as $record) {
        // Process each record here
    }
});

In this example, the chunk() method is called on a query builder instance for the my_table table, specifying that the results should be ordered by the id column. The first parameter of the chunk() method is the number of records to retrieve per chunk (in this case, 100), and the second parameter is a callback function that will be called for each chunk of records retrieved.

Within the callback function, you can process each record as needed. The $records parameter passed to the callback function will be an array containing up to 100 records from the database.

By using the chunk() method with Eloquent, you can efficiently process large datasets without overloading your application’s memory or performance.

I hope you get an idea about laravel model attributes.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

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

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype