Search code examples
laraveldatabaseeloquenttags

Foreach Storing last data form array in Laravel. Help Plz


I have Tag table, Post Table and PostHasTag Table. But when I go to store my tags in, PostHasTag with post_id and tag_id.

I am using foreach loop for storing tags, but it just stored last tag. Now where is my problem?

public static function postHasTags($post_id, $tag_ids)
    {
        $store = new PostHasTag();
        foreach ($tag_ids as $tag_id) {
            $checkTag = PostHasTag::where('post_id', $post_id)->where('tag_id', $tag_id)->get();
            if (count($checkTag) > 0) {
                return back()->with('error', 'Tag already exists');
            } else{
                $store->post_id = $post_id;
                $store->tag_id = $tag_id;
                $store->save();
            }
        }
        return $store;
    }

Solution

  • Line $store = new PostHasTag(); should be inside foreach() loop, so it should look like this :

     public static function postHasTags($post_id, $tag_ids)
        {
            foreach ($tag_ids as $tag_id) {
                $checkTag = PostHasTag::where('post_id', $post_id)->where('tag_id', $tag_id)->get();
                if (count($checkTag)) {
                    return back()->with('error', 'Tag already exists');
                } else{
                    $store = new PostHasTag(); // Better to put it here
                    $store->post_id = $post_id;
                    $store->tag_id = $tag_id;
                    $store->save();
                }
            }
            return $store;
        }
    

    But in this case you are returning only last created PostHasTag. If you need all of them, then push each PostHasTag in a collection and return it.