'How to write this query in Laravel Eloquent

The query is SELECT country, count(*) as count FROM visitors GROUP BY country ORDER BY count DESC. How to write with Visitor model eloquently?



Solution 1:[1]

Visitor::query()->groupBy('country')->orderByDesc('count')->select('country' ,DB::raw('COUNT(1) as count'))->get()

Solution 2:[2]

You could try somthing like this

Visitor::select('country')
     ->withCount('id')
     ->groupBy('country')
     ->latest()
     ->get()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 amirhosein hadi
Solution 2