Home > Back-end >  Laravel Create Method Syntax Alternative
Laravel Create Method Syntax Alternative

Time:11-17

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.

CodePudding user response:

You could do

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

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

  • Related