Dev
Dev

Reputation: 1073

How to insert in Laravel?

I have output object $product after inserting data into table Product:

$product = Product::create($data);

In model Product I have:

public function images()
    {
        return $this->hasMany("App\ProductImage");
    }

The I try to add images to table product_images:

$product->images()->save(new ProductImage(UploadFiles::$files));

Relationship beetwen tables is product.id = product_images.

So, after inserting I get message:

General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `product_images` (`product_id`) values (21))

Upvotes: 0

Views: 185

Answers (1)

craig_h
craig_h

Reputation: 32734

OK, firstly let's deal with saving one image:

Assuming you have a product_images table with id, image, product_id, you would attach an image like so:

$image = new ProductImage(['image' => 'myImage.jpg']);
$product->images()->save($image);

Now it looks like you have an array, so you can't save that directly, you need to put it in a for loop. I don't know the format of your UploadFiles::$files, but I'll assume it's just a list of file names to save:

$files = UploadFiles::$files;

foreach($files as $file){
  $image = new ProductImage(['image' => $file]);
  $product->images()->save($image);
}

Alternatively, you could create the whole thing as an array and use saveMany, which would be better:

$files = UploadFiles::$files;
$productImages = [];

foreach($files as $image){
  $productImages[] = new ProductImage(['image' => $image]);
}

$product->images()->saveMany($productImages);

Upvotes: 2

Related Questions