ene's avatar
Level 2

Array to string conversion

i am trying to upload multiple image for a single product and i am getting this error Array to string conversion

  public function create()
    {
        if (auth()->check()) {
            $this->validate();
            $product =   Product::create([
                'user_id' => auth()->user()->id,
                'title' => $this->title,
                'category_id' => $this->category,
                'price' => $this->price,
                'location' => $this->location,
                'body' => $this->body,

            ]);


            foreach ($this->images as $key => $image) {
                $this->images[$key] = $image->store('images','public');
            }
            ProductImage::create([
                'product_id' => $product->id,
                'filename' =>  $this->images,
            ]);
0 likes
3 replies
RayC's avatar

Are you meaning to store the images array here:

// Inside your loop as well
$this->images[$key]; // This should be $key

ProductImage::create([
	'product_id' => $product->id,
	'filename' =>  $this->images, // This is trying to convert the images array to a string.
]);

There are a few issues with your code. You could simplify it by using this package (no reason to reinvent the wheel):

https://spatie.be/docs/laravel-medialibrary/v10/introduction

jpmg's avatar
     foreach($this->images as $mediaFiles) {
           $path=   $mediaFiles->store("/public/images");
             ProductImage::create([
             	'product_id' => $product->id,
                'filename' =>  $path]);
     }//storeimage
Snapey's avatar
Snapey
Best Answer
Level 122
foreach ($this->images as $image) {
    ProductImage::create([
        'product_id' => $product->id,
        'filename' =>  $image->store('images','public');
    ]);
}

but the images are perfect? You don't need to downsize or crop them?

Please or to participate in this conversation.