Search code examples
laravellaravel-5laravel-storage

Multiple upload using Laravel Storage


I was try to upload multiple files using Storage so here's my code:

public function store(Request $request)
{
    $gallery  = new Gallery();
    $gallery->name = $request->name;
    $gallery->description = $request->description;
    $gallery->save();

    $path = 'public'.'/'.str_slug($request->name);
    Storage::makeDirectory(str_slug($request->name));

    $image = new Image();
    if ( is_array($request->images)) {
        foreach ($request->images as $file) {
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->save();
            Storage::putFileAs($path, $file);
        }
    } else {
            $image->gallery_id = $gallery->id;
            $image->name = $request->images->getClientOriginalName();
            $image->save();
    }
}

and I already setup my form like this:

<div class="form-group">
    <label for="images" class="col-md-2 control-label">Images</label>
    <div class="col-md-6">
        <input type="file" class="form-control" name="images[]" id="images[]" multiple>
    </div>
</div>

it give me an errors like this:

"Type error: Too few arguments to function Illuminate\Filesystem\FilesystemAdapter::putFileAs(), 2 passed in E:\laragon\www\blog\vendor\laravel\framework\src\Illuminate\Filesystem\FilesystemManager.php on line 343 and at least 3 expected ◀"

so the problem is it the way I check that it has multiple file using is_array is right? and the second what can cause this problems?


Solution

  • Pass the 3rd argument to the putFileAs method

    if( is_array($request->images)){
        foreach ($request->images as $file) {
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $file->getClientOriginalName();
            $image->extension = $file->extension();
            $image->size = 555;
            $image->save();
    
            // Or any custom name as the third argument
            Storage::putFileAs($path, $file, $file->getClientOriginalName());
        }
    } else {
            $image = new Image();
            $image->gallery_id = $gallery->id;
            $image->name = $request->images->getClientOriginalName();;
            $image->save();
    
            // Or any custom name as the third argument
            Storage::putFileAs($path, $request->images, $request->images->getClientOriginalName());
    }
    return back();
    

    Documentation