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

2

10

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?

Stephanistephania answered 17/10, 2017 at 16:16 Comment(0)
A
3
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.

Abadan answered 7/11, 2017 at 10:13 Comment(0)
S
0

Per Laravel 5.3 documentation, look into Automatic Streaming

If you would like Laravel to automatically manage streaming a given file to your storage location, you may use the putFile or putFileAs method. This method accepts either a Illuminate\Http\File or Illuminate\Http\UploadedFile instance and will automatically stream the file to your desire location:

You can upload file with streaming like this

$file = $request->file('file');
$path = \Storage::putFile('photos', $file);

Where your form input is

<input type="file" name="file">
Starlight answered 18/10, 2017 at 19:59 Comment(4)
If you want to upload file with different name, use putFileAs.Starlight
$file is instance of UploadedFile, so you can look there for available methodsStarlight
As per my question, I'm not uploading a file, and I'm not streaming a file to another file. I am trying to write a plain-text file that I am building in-code in a streaming fashion. I have managed to write this very easily using fopen and fwrite, but would prefer the built-in Storage methods. I'm beginning to think it's not possible.Stephanistephania
Sorry, I was tired when I responded to this. You could try $file_name = 'test.txt'; $is_created = Storage::put($file_name, 'Hello'); Storage::append($file_name, ', '); Storage::append($file_name, 'world'); Storage::append($file_name, '!'); Starlight

© 2022 - 2024 — McMap. All rights reserved.