Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a resource to write line by line but still use Laravel's built in Storage?

I want to use Storage::put to write a file. The file is potentially very large (>100MB), so I want to utilise a stream so I don't blindly place everything into memory.

I'm going to be making multiple API requests, and then looping through their results, so the data I'll be getting back isn't an issue, it'll be limited to sensible amounts.

According to the documentation, I need to use:

Storage::put('file.xml', $resource);

But what would $resource be here?

Traditionally when writing files using PHP I have done it with a combination of fopen, fwrite and fclose in order to write 'line by line'. I'm building the file up by looping through various Collections and utlising various APIs as I go, so $resource is NOT a file pointer or file reference as is talked about elsewhere in the documentation.

So, how can I write line by line using a stream and Laravel's Storage?

like image 574
Mike Avatar asked Oct 17 '17 16:10

Mike


People also ask

What is php artisan storage Link?

php artisan storage:link. Once a file has been stored and the symbolic link has been created, you can create a URL to the files using the asset helper: echo asset('storage/file.txt'); You may configure additional symbolic links in your filesystems configuration file.

How can I get storage path in Laravel 8?

You can use the storage_path(); function to get storage folder path.

How do I save to storage folder in Laravel?

Now, if you need to change the directory and store into the storage folder directly, you need to change something in the filesystems. php file. 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), ], Here, this line of code 'root' => storage_path('app'), responsible to define where to store.

How do I delete files from storage in Laravel?

One way to delete a file from the public directory in Laravel is to use the Storage facade. To delete a file, you will need to follow the following steps: Step 1: Check to ensure that the folder and file exist. Step 2: Delete the required file.


1 Answers

Storage::put('file.xml', $resource);

But what would $resource be here?

$resource is your data that you prepare to write to disk by code.

If you want to write the file with a loop you must use the Storage::append($file_name, $data); as wrote before by ljubadr

I wrote $data but you can use any name you want for a variable inside a loop.

like image 194
Alviero Avatar answered Oct 16 '22 05:10

Alviero