The Tag model represents tags that can be applied to blog posts. Tags provide flexible labeling and help users discover related content. Posts can have multiple tags through a many-to-many relationship.Namespace:App\Models\TagFile:app/Models/Tag.php:7
Many-to-many relationship with the Post model.Returns:BelongsToMany<Post>Pivot table:post_tag
// Get all posts with a specific tag$tag = Tag::where('name', 'laravel')->first();$posts = $tag->posts;// Get tags with post count$popularTags = Tag::withCount('posts') ->orderBy('posts_count', 'desc') ->take(10) ->get();
// Get all posts with a specific tag$laravelPosts = Post::whereHas('tags', function($query) { $query->where('name', 'laravel');})->get();// Get posts with multiple tags (AND)$posts = Post::whereHas('tags', function($query) { $query->where('name', 'laravel');})->whereHas('tags', function($query) { $query->where('name', 'php');})->get();// Get posts with any of multiple tags (OR)$posts = Post::whereHas('tags', function($query) { $query->whereIn('name', ['laravel', 'php', 'mysql']);})->get();
Consider normalizing tag names to lowercase to prevent duplicates like “Laravel” and “laravel”. Implement this in a model accessor or when creating tags.
Use firstOrCreate() when adding tags to prevent duplicate tag creation from user input.