How can I solve "Type error: Argument 2 passed ... must be an instance of Symfony \ Component \ HttpFoundation \ File \ UploadedFile"?

My controller looks like this:

public function store(CreateProductRequest $request)
{
    ...
    $result = $this->product_service->createProduct($param,$photo);
    ...
}

      

My service is like this:

public function createProduct($param, UploadedFile $photo=null)
{
    dd($photo);
    if($photo) {
        $fileName = str_random(40) . '.' . $photo->guessClientExtension();
        $param['photo'] = $fileName;
        $param['photo_list'] = json_encode(['id'=>1,'name'=>$fileName]);
    }
    ...
    if(is_array($result) && count($result)>1 && $result[0])
        $this->savePhoto($photo, $fileName,$result[1]->id);
    ...
    return $result;
}

private function savePhoto(UploadedFile $photo, $fileName, $id)
{
    $destinationPath = public_path() . DIRECTORY_SEPARATOR . 'img'. DIRECTORY_SEPARATOR .'products'.DIRECTORY_SEPARATOR.$id;
    $photo->move($destinationPath, $fileName);
    resize_image($fileName,250,'products',$id);
    return $fileName;
}

      

Symfony \ Component \ HttpFoundation \ File \ UploadedFile looks like this: https://pastebin.com/KLfnXZJV

When the variable is $photo

not an array or only 1 data I do dd($photo);

, it displays the result

But when the variable $photo

is an array, I do dd($photo);

, there is an error:

Type error: argument 2 passed to App \ Services \ ProductService :: createProduct () must be an instance of Symfony \ Component \ HttpFoundation \ File \ UploadedFile, given array

How can I solve this problem?

+3


source to share


1 answer


The problem is that you either get one file or an array of files. Does product support create more than one file download? If not, you can do something like this:

// If file is inside an array, pull it out
if (is_array($photo) && $photo[0] instanceof UploadedFile) {
    $photo = $photo[0];
}

// Run upload
$result = $this->product_service->createProduct($param, $photo);

      

If you need to upload multiple files, there are a few things to do. First, you cannot inherit your method like UploadedFile

. Instead, enter it as an array:

public function createProduct($param, array $photos = [])

      



And then in your logic, createProduct

you will need to go through the array of photos and save them individually.

Finally, in your controller, you will need to do the opposite of the first suggestion, and instead of fetching from an array, you need to put it in one:

if ($photo instanceof UploadedFile) {
    $photo = [$photo];
}

      

+1


source







All Articles