How to make a selection of tags and count the number of materials in Laravel?

Hello!
Please tell me the best solution for the following problem.
There is a list of tags (about 2000). On a page a list of tags indicating the number of articles attached to them using Laravel's Query Builder.
C sample tags, no problems.
$request = DB::table('tags')->paginate(150);
What we need to add to the result and the amount of materials in table contentwhere content.tag_id equal tags.tag_id.
Thank you!
June 7th 19 at 14:22
2 answers
June 7th 19 at 14:24
1. To adjust the relations
Usually the tags are working with Many To Many or Many To Many Polymorphic Relations

2. Now we need to write the queries to relations
$tags = App\Tag::withCount('contents')->get();
The number of articles is stored in the contents_count
If you want to filter the articles, then
$tags = App\Tag::withCount(['contents' => function ($query) {
 $query->where('status', 1);
}])->get();


June 7th 19 at 14:26
Please tell me the best solution for the following problem.

Eloquent: Relationships
...using Laravel Query Builder.

Database: Query Builder

Find more questions by tags MySQLLaravel