What is the best strategy for creating a record and associating with another by means of a pivot table?

1

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

I then retrieve the id of the created record and associate this record with a category by means of the pivot table:

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 wondering if this would be the best solution?

The code for this model is available at: PostController

    
asked by anonymous 17.04.2017 / 13:52

1 answer

1

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

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!']);
}
    
18.04.2017 / 02:32