How to create Database for single post and multiple images?

When I have a post and images relationship "One to Many", Post has many images and image belongs to one post. Should I create database tables individually for Posts and Images?, just like we create two models? Or should I place image1, image2, image3 colums in posts table? Please suggest a best solution.

w1n78 replied 3 months ago
// set up the relationship via model classes

// Post model

public function images()
  return $this->hasMany(Image::class);

// Image model
public function post()
  return $this->belongsTo(Post::class);

// now that you have that, you can use eloquent to do a one to many insert
Shiva Sheshendra replied 3 months ago

Thank you for your reply. So I guess, I also need to create two tables. One for Post and another one for Images. Is that correct?

Alex Nastase replied 3 months ago

Hi Shiva, in my opinion, ill go with two tabels (posts and media) and if i have a thumbnail image, i will save it in post table. You will always need the post image but not the post gallery images. The relationships of the tables will be post - hasMany and media - belongsTo.

I hope this help you.

Shiva Sheshendra replied 3 months ago

Thank you Alex, For blog, I need only one image. However, for ecommerce website, I may need multiple images for one product. That was the reason, I asked this question.

Mohammad Hammal replied 3 months ago

of course, you need tow tables to do it the right way because you don't know the number of images the user can upload for one product

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us