klp klp - 4 months ago 12x
JSON Question

Insert JSON data to file with Laravel

I am inserting JSON data to a file with Laravel, I have 300 000 records and I want to insert them by block of 5000 records.

public function fileput($start,$end,$n) {
$final = [];
$res = DB::table('company')
->Where('company_id', '>',$start)
->Where('company_id', '<',$end)

foreach ($res as $k => $v) {
$id = $v->company_id;
$index = 10000000 + $id;
$arr = array('index' => ['_id' => $index]);
$ind = json_encode($arr);
$data = json_encode($v);
array_push($final, $ind, $data);
$written = File::put('file.txt', $final);

Problem is, after entering first 5000, when incrementing to 10000, first 5000 records got erased.

Therefore how can I insert all the records in one file?


Try using File::append() instead of File::put().