Insert and attach tag to the post in same time I created a form with title, body and tag input and there are 3 tables: posts, tags and post_tag.

Now I use this function to add new tags and attach them to the post

postcontroller.php

 public function store(Request $request)
    {
        $input = $request-&gt;all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=&gt;$tag]);
        $tagid = $tagdone-&gt;id; //insert tag to tags table

        $posts = Posts::create($input); //insert posts table
        $postid = $posts-&gt;id; 

        Posts::find($postid)-&gt;tags()-&gt;attach($tagid); //attach tag to the post
    }


There are actually 3 actions at the same time. But I think there are better ways than this one, so I'd like some feedback on what I've written.
Use the following:

 public function store(Request $request)
    {
        $input = $request-&gt;all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=&gt;$tag]);
        $tagid = $tagdone-&gt;id; //insert tag to tags table

        $posts = Posts::create($input); //insert posts table

        $posts-&gt;tags()-&gt;attach($tagid); //attach tag to the post
    }


This will reduce your database queries by one SELECT by removing Posts::find($postid).



Apart from the above, is there any reason for using three database tables? Just from the code provided it doesn't seem to be necessary and I would only use one table with all three inputs. Or at least reduce to two database tables as follows:

 public function store(Request $request)
    {
        $input = $request-&gt;all(); //get inputs value

        $tag = $input['tag'];
        $tagdone = Tag::create(['name'=&gt;$tag]); //insert tag to tags table

        $input['tagid'] = $tagdone-&gt;id;

        $posts = Posts::create($input); //insert posts table, including tagid
    }