Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vandan's avatar
Level 13

laravel optimize query with cursor or chunk

Hello everyone i used to optimize query using cursor method but i dont know how to implement cursor in wherehas query so please suggest anyone how to use it

		foreach(Product::cursor() as $product){
        		$product->whereHas('supplier', function (Builder $query) {
            		$query->where('sys_state','!=','-1');
        		})
        		->whereHas('customer', function (Builder $query) {
            		$query->where('sys_state','!=','-1');
        		})
        		->where('sys_state','!=','-1')
        		->with('supplier')
        		->orderBy('id','desc')
        		->get();
    		}

orelse what is best for use of cursor or chunk i have 1 lakh data in products

0 likes
5 replies
LaryAI's avatar
Level 58

You can use the cursor() method to optimize your query. The cursor() method will return a cursor instance which can be used to iterate over the results. You can use the whereHas() method within the cursor() method to filter the results. Here is an example:

Product::cursor()
    ->whereHas('supplier', function (Builder $query) {
        $query->where('sys_state','!=','-1');
    })
    ->whereHas('customer', function (Builder $query) {
        $query->where('sys_state','!=','-1');
    })
    ->where('sys_state','!=','-1')
    ->with('supplier')
    ->orderBy('id','desc')
    ->each(function ($product) {
        // Do something with the product
    });

The cursor() method is more efficient than the chunk() method when dealing with large datasets. The chunk() method will load the entire dataset into memory, while the cursor() method will only load one record at a time.

jlrdw's avatar

If you replace ->get(); with ->paginate(); what happens.

1 like
vandan's avatar
Level 13

@jlrdw i try for example with paginate(25) so return only 25 records i want all datas

jlrdw's avatar

@vandan for all you don't chunk or paginate. However if it is a lot of data you may need to paginate.

1 like
vandan's avatar
Level 13

@jlrdw yes instead of using chunk or paginate i m using server side processing it will give me superfast retrieve data with using paginate

Please or to participate in this conversation.