Laravel Spatie Medialibrary:通过REST API上传多个图像

时间:2019-09-04 19:24:43

标签: laravel

我在Laravel应用程序中使用Spatie MediaLibrary库。我想通过REST API将0张或更多照片上传到我的应用。

photo属性包含1个文件时,我可以使它工作

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);
}

邮递员请求如下所示: enter image description here

我知道要更改代码,以便它可以处理请求中的多张照片。我在上面的控制器中使用以下代码来做到这一点:

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

并且我将属性更改为photos[],而不是photo

enter image description here

代码甚至永远也不会进入foreach循环。

有人暗示如何解决吗?

2 个答案:

答案 0 :(得分:0)

今天早上尝试了其他方法,此方法有效。显然,Spatie媒体库具有一个名为addMultipleMediaFromRequest的功能。现在完整的代码是

public function store(Request $request)
{
   $request->validate([
        'name'          =>      'required',
        'slug'          =>      'required',
        'description'   =>      'required',
        'price'         =>      'required|integer',
        'photo'         =>      'nullable'
    ]);

    $listing =  Listing::Create([
        'user_id'       =>      auth('api')->user()->id,
        'name'          =>      $request->name,
        'slug'          =>      $request->slug,
        'description'   =>      $request->description,
        'price'         =>      $request->price,
    ]);

    if ($request->hasFile('photo')) {
        $fileAdders = $listing->addMultipleMediaFromRequest(['photo'])
            ->each(function ($fileAdder) {
                $fileAdder->toMediaCollection('photos');
            });
    }

    return new ListingResource($listing);
}

在邮递员中,我将其称为: enter image description here

答案 1 :(得分:0)

我设法上传了多个文件,如下所示:

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

检查一下:
https://github.com/spatie/laravel-medialibrary/issues/227#issuecomment-220794240