How to create a empty file and append by lines Laravel?

Viewed 110

I have the function that accepts array of columns and try to write them into file:

private function toCSV($data, $checkers,  $filename, $delim)
{

    foreach ($data as $row) {
        $str = [];
        foreach ($checkers as $checkername => $checker) {
            foreach ($checker as  $key) {
                $str[] =  $row->type == $key ? $row->value :  'NULL';
            }
        }

        Storage::append($this->uploadpath . $checkername . "_" . $filename, implode($delim, $str));
    }
}

Usage is:

   foreach ($rows as $columns) {
        $this->toCSV($columns, $chekerformats,  $filename, ':');
    }

Problem is that file must be createad for each element of foreach ($checkers as $checkername => $checker) {}. But now it creates only one file and appends data. After complete I have to return a path to files name to the client.

Could you help me how to fix my code?

1 Answers

You get only one file because the name of that file corresponds to last checkername. To fix that you should move the storage sentence inside to the checker's loop. Then you should keep the files path into an array and return that collection.

private function toCSV($data, $checkers,  $filename, $delim)
{
    $files_path = [];
    foreach ($data as $row) {
        $str = [];
        foreach ($checkers as $checkername => $checker) {
            foreach ($checker as  $key) {
                $str[] =  $row->type == $key ? $row->value :  'NULL';
            }
            $file_path = $this->uploadpath . $checkername . "_" . $filename;
            Storage::append($file_path, implode($delim, $str));

            $files_path[]= $file_path;
        }
    }
    
    return $files_path;
}
Related