cviebrock / eloquent-taggable

Easily add the ability to tag your Eloquent models in Laravel.
MIT License
537 stars 72 forks source link

Display all tags with count #96

Closed timgavin closed 5 years ago

timgavin commented 5 years ago

Is there a way to display all tags (not popular tags, but ALL tags) with a count of how many times they have been used?

cviebrock commented 5 years ago

Tags are just regular Eloquent models, so you can query them directly. See https://laravel.com/docs/5.8/eloquent-relationships#counting-related-models

Something like this would probably work (untested):

$tags = Tag::withCount('taggedModels')->get();
tfevan commented 5 years ago

In your controller

$tags = Post::allTagsList();

In your views

@foreach ($tags as $name => $count) {

    {{ $name }} // Get the tag name
    {{ $count }}// Get the count value

        }
@endforeach

Hope this helps :)

devkornev commented 5 years ago

$tags = Tag::withCount('taggedModels')->get();

Call to undefined method Cviebrock\EloquentTaggable\Models\Tag::taggedModels()

$tags = Post::allTagsList(); dd($tags);

"tag1,tag2,...,tag100500"

Both methods do not give results.

cviebrock commented 5 years ago

You are right: neither of those options work.

However, getPopularTags just does a count on the tags, so this should give you what you want:

        $tags = app(TagService::class)
            ->getPopularTags(null, null, 0)
            ->pluck('taggable_count', 'normalized')
            ->toArray();