src/Services/TagService.php
public function getPopularTags(int $limit = null, $class = null, int $minCount = 1): Collection
    {
        $tagTable = $this->getQualifiedTagTableName();
        $pivotTable = $this->getQualifiedPivotTableName();

        $sql = "SELECT t.*, COUNT(t.tag_id) AS taggable_count 
            FROM {$tagTable} t 
            LEFT JOIN {$pivotTable} tt ON tt.tag_id=t.tag_id";
        $bindings = [];

        if ($class) {
            $sql .= ' WHERE tt.taggable_type = ?';
            $bindings[] = ($class instanceof Model) ? get_class($class) : $class;
        }

        // group by everything to handle strict and non-strict mode in MySQL
        $sql .= ' GROUP BY t.tag_id, t.name, t.normalized, t.created_at, t.updated_at';

        if ($minCount > 1) {
            $sql .= ' HAVING taggable_count >= ?';
            $bindings[] = $minCount;
        }

        $sql .= ' ORDER BY taggable_count DESC';

        if ($limit) {
            $sql .= ' LIMIT ?';
            $bindings[] = $limit;
        }

        return $this->tagModel::fromQuery($sql, $bindings);
    }
public function getPopularTags(int $limit = null, $class = null, int $minCount = 1): Collection
    {
        $tagTable = $this->getQualifiedTagTableName();
        $pivotTable = $this->getQualifiedPivotTableName();

        $sql = "SELECT t.*, COUNT(t.tag_id) AS taggable_count 
            FROM {$tagTable} t 
            LEFT JOIN {$pivotTable} tt ON tt.tag_id=t.tag_id";
        $bindings = [];

        if ($class) {
            $sql .= ' WHERE tt.taggable_type = ?';
            $bindings[] = ($class instanceof Model) ? get_class($class) : $class;
        }

        // group by everything to handle strict and non-strict mode in MySQL
        $sql .= ' GROUP BY t.tag_id, t.name, t.normalized, t.created_at, t.updated_at';

        if ($minCount > 1) {
            $sql .= ' HAVING taggable_count >= ?';
            $bindings[] = $minCount;
        }

        $sql .= ' ORDER BY taggable_count DESC';

        if ($limit) {
            $sql .= ' LIMIT ?';
            $bindings[] = $limit;
        }

        return $this->tagModel::fromQuery($sql, $bindings);
    }
Get the most popular tags, optionally limited and/or filtered by class.

@param int $limit
@param \Illuminate\Database\Eloquent\Model|string|null $class
@param int $minCount

@return \Illuminate\Database\Eloquent\Collection