9

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?

Daniel Dewhurst
  • 2,298
  • 1
  • 17
  • 35
Mike
  • 8,259
  • 8
  • 41
  • 93

2 Answers2

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.

Alviero
  • 46
  • 5
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">
ljubadr
  • 1,899
  • 1
  • 14
  • 18
  • If you want to upload file with different name, use `putFileAs`. – ljubadr Oct 18 '17 at 20:07
  • `$file` is instance of [UploadedFile](https://laravel.com/api/5.3/Illuminate/Http/UploadedFile.html), so you can look there for available methods – ljubadr Oct 18 '17 at 20:08
  • 1
    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. – Mike Oct 19 '17 at 08:29
  • 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, '!'); ` – ljubadr Oct 19 '17 at 12:55