1

I have Post table and images table that have one to many relationship.

Post Model Code

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

I take from the user 3 images and I want to insert them in the images table with the post id.

For example

firstImage.jpg with post id 1

secondImage.jpg with post id 1

thirdImage.jpg with post id 1

Question is

How I insert the three images at the same time with id 1 in three columns

What I have tried

I have made a for loop that insert 3 times in the table but I know it is not a good practice and here is the code.

for($x = 0; $x < 3; $x++) {
$image = new PostImage;
$image -> post_id   = $ad -> id;
$image -> image     = $images_name[$x];
$image -> save();
}
Frank
  • 13
  • 3
  • Duplicate of: http://stackoverflow.com/questions/29723865/how-to-insert-multiple-rows-from-a-single-query-using-eloquent-fluent – ad_on_is Apr 21 '17 at 15:19
  • Possible duplicate of [How to insert multiple rows from a single query using eloquent/fluent](http://stackoverflow.com/questions/29723865/how-to-insert-multiple-rows-from-a-single-query-using-eloquent-fluent) – ad_on_is Apr 21 '17 at 15:21

1 Answers1

1

There is nothing wrong with this approach if you need to insert just 3 images. However, if you want to insert hundreds of images, I'd recommend you to use the insert() method which will create just one query instead of creating 100 queries for inserting 100 images:

$array = [];
foreach ($images_name as $name) {
    $array[] = ['post_id' => $ad->id, 'image' => $name];
}
PostImage::insert($array);
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • they wont be more than 3 images so what is the best solution in this case? – Frank Apr 21 '17 at 15:02
  • @Frank for 3 images I'd stick with your solution, but I'd change the code to something like `foreach ($image_name as $name) { PostImage::create(['post_id' => $ad->id, 'image' => $name]); }` – Alexey Mezenin Apr 21 '17 at 15:04