Several relationships in one model in Laravel

31 views Asked by At

How can I save a model with two relationships in Laravel?

I have 3 model:

Model user:

    id
    name

Model post:

    id
    text
    user_id

Model comment:

    id
    message
    post_id
    user_id

Create comment:

#find post
$post = Post::find(1);

#Create comment and connect to post 
$comment = $post->comments()->create($validated);

#How connect user?

How connect user?

There are many examples in the documentation, but nothing like this.

1

There are 1 answers

2
kris gjika On BEST ANSWER

While $model->relation()->create([]) creates a related model, in the context of the relation, there isn't a way to give multiple contexts for multiple relations. So you need to add the user_id yourself the data passed to create

#find post
$validated = $request->validated();
$validated['user_id'] = $request->user()->id; // user performing the request
$post = Post::find(1);

#Create comment and connect to post 
$comment = $post->comments()->create($validated);