1

I'm building relationships between the users and posts tables. I'm wondering if there is a way to write this differently than this syntax?

$request->user()->posts()->create([
  'body' => $request->body
]);

Using syntax like this below how can achieve the same result as above?

Post::create([
  'body' => $request->body,
]);

I'm curious because I like to keep the same patterns.

1
  • you would add the user_id field to that array (which would have to be fillable on the model) ... i would suggest using the first method and let eloquent handle the needed key for the relationship Commented Nov 17, 2021 at 4:47

1 Answer 1

1

You could do

Post::create([
    'user_id' => Auth::user()->id,
    'body' => $request->body,
]);

But for relations it's best to do your first solution.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.