Example #1
0
 public static function saveTags($tags, Post $post, $type)
 {
     // Remove all previous post and tag relationships
     $postTags = PostTag::where('post_id', $post->id)->where('type', $type)->delete();
     $tagGroup = explode(',', $tags);
     if ($tags) {
         foreach ($tagGroup as $key => $tagName) {
             $tag = Tag::where('name', $tagName)->first();
             // Refrain from insertion if the tag already exists.
             if (!$tag) {
                 $tag = Tag::create(['name' => $tagName, 'slug' => str_slug($tagName), 'type' => $type]);
             }
             // Create new post and tag relationships
             PostTag::create(['post_id' => $post->id, 'tag_id' => $tag->id, 'type' => $type]);
         }
     }
 }