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

Badrus_junior's avatar

chunk to array

i working on medium size of data, i wanna insert my chunk to a new array, but when i dump it gots nothing (empty). can you help me where's wrong with my code. thanks

$data = []; Voucher::with(['merchant:id,nama','offer:id,nama','payment:id,nama']) ->select('voucher.*') ->chunk(1000, function($vouchers) use($data){ foreach ($vouchers as $v){ $data[] = array( 'ID' => $v->id, 'Date' => date('d/m/Y',strtotime($v->qty)), ); } });

    DD($data);
0 likes
1 reply
DhPandya's avatar

@badrus_junior You have to reference your $data when you're using it with the callback functions. Like in the below example.

$data = [];
        Voucher::with(['merchant:id,nama','offer:id,nama','payment:id,nama'])
        ->select('voucher.*')
        ->chunk(1000, function($vouchers) use(&$data){
            foreach ($vouchers as $v){
                $data[] = array( 'ID' => $v->id, 'Date' => date('d/m/Y',strtotime($v->qty)), );
            }
        });

Please or to participate in this conversation.