'Laravel Spatie Medialibrary: upload multiple images through REST API

I'm using the Spatie MediaLibrary library in a Laravel application. I want to upload 0 or more photos to my app via a REST API.

I can get it to work when the photo attribute contains 1 file

public function store(Request $request)
{
    $request->validate([
        'name'          =>      'required',
        'slug'          =>      'required',
        'description'   =>      'required',
        'price'         =>      'required|integer',
        'photo'         =>      'nullable|file'
    ]);
    $listing =  Listing::Create([
        'user_id'       =>      auth('api')->user()->id,
        'name'          =>      $request->name,
        'slug'          =>      $request->slug,
        'description'   =>      $request->description,
        'price'         =>      $request->price,
    ]);
    // stores the photo
    if ($request->hasFile('photo')) {
        $listing->addMediaFromRequest('photo')->toMediaCollection('photos');
    }
    return new ListingResource($listing);
}

The postman request looks as follows: enter image description here

I know want to change the code so it can handle multiple photos in the request. I'm using the following code in the controller above to do so:

if ($request->hasFile('photo')) {
   foreach ($request->input('photo', []) as $photo) {
       $listing->addMediaFromRequest('photo')->toMediaCollection('photos');
   }
}

and I have changed the attribute to photos[] instead of photo.

enter image description here

The code never goes into the foreach loop even.

Anyone has a hint on how to solve this?



Solution 1:[1]

I managed to upload multiple files like this:

if($request->file('photos')) {
    foreach ($request->file('photos') as $photo) {
        $post->addMedia($photo)->toMediaCollection('post');
    }
}

Check this out:
https://github.com/spatie/laravel-medialibrary/issues/227#issuecomment-220794240

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Davide Casiraghi