Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vinoth06's avatar

Best way to save with one to many relationship

I have three tables,

  1. Users [fields: id, name, email]
  2. Posts [fields: id, user_id, post, category ]
  3. Comments [fields: id, user_id, post_id, message]

Model

  1. user->hasMany(posts), user->hasMany(comments)
  2. post->hasMany(comments), post->belongsTo(user)
  3. comments->belongsTo(posts), comments->belongsTo(user)

Now am a logged in user and I need to comment on a post. So the user and post are already created and now we need to create comment with post and user id on it.

what would be the best way to do that

0 likes
8 replies
goatshark's avatar

@VINOTH06 Assuming you have the post...

$post->comments()->create([array-of-comment-data]);

Btw, that should return the new comment, so you can:

$new_comment = $post->comments()->create([array-of-comment-data]);
vinoth06's avatar

@goatshark hope we need to make user_id to be fillable on comments create. Please correct me if am wrong.

goatshark's avatar

@vinoth06 I think you'll need either user_id or post_id to be fillable on comments.

If user_id is fillable, it would look something like this, where "array-of-comment-data" includes the user_id.

$post->comments()->create([array-of-comment-data]);

If post_id is fillable, it would look something like this, where "array-of-comment-data" includes the post_id.

$user->comments()->create([array-of-comment-data]);
vinoth06's avatar

@goatshark OK. Thank you. So we must make anyone to be fillable. So no way to make without fillable by like associate().

Please or to participate in this conversation.