I have a problem with laravel collection with chunk result. It run only one time in loop.
I have 204 elements in array and I want to split it as 100 each by using laravel collection helper. It must run in three times but I got only once.
private function __migrateDistricts()
{
DB::beginTransaction();
try {
$file = 'resources/csv/districts.csv';
$csv = array_map('str_getcsv', file($file));
$table = 'districts';
$collection = collect($csv);
$arr_districts = array();
foreach ($collection->chunk(100) as $districts) {
foreach ($districts as $dist) {
array_push($arr_districts, $this->__transformDistricts($dist));
}
DB::table($table)->insert($arr_districts);
DB::commit();
}
} catch (\Exception $e) {
DB::rollBack();
}
}
private function __transformDistricts($district)
{
$code = substr($district[3],0,2);
$pro = DB::table('provinces')->where('code', $code)->first();
return [
'province_id' => $pro->id,
'name_kh' => $district[1],
'name_en' => $district[2],
'code' => $district[3],
];
}
After I run the I got only 100 records in table. It should be 204 records in table. What is wrong with my code? Thanks