insert and attach tag to the post in same time

Posted 3 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


 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.

Reply to

Use Markdown with GitHub-flavored code blocks.