mohammad6006
4 years ago

insert and attach tag to the post in same time

Posted 4 years ago by mohammad6006

I'm beginner in laravel. 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->all(); //get inputs value

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

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

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

Actually 3 action in same time. But I think there are better ways than this one, so I'd like some feedback on what I've written.

Please sign in or create an account to participate in this conversation.