What is the best strategy to create a record and associate with another by means of a pivot table?

Asked

Viewed 28 times

1

The section below takes the user’s session data, uses the method posts present in the model User to create a new post in the bank.

Later I recover the id of the created record and associate this record to a category through the table pivot:

if(\Auth::user() && $dbId = \Auth::user()->posts()
                                         ->create($request->except(['categoria']))) {

            $post = Post::find($dbId->id);
            $post->categorias()->attach($request->input('categoria'));

            return redirect('/painel/post')
                    ->with(['status' => 'success', 'msg' => 'Post criado com sucesso!']);
}

But I’m not sure if this is the best solution?

The code for this model is available in: Postcontroller

1 answer

2


I would do so, it would be the logical way to take advantage of the instance created by the method create:

if(\Auth::user()) 
{
    $post = \Auth::user()->posts()->create($request->except(['categoria']))
    $post->categorias()->attach($request->input('categoria'));

    return redirect('/painel/post')
               ->with(['status' => 'success', 'msg' => 'Post criado com sucesso!']);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.