Hugo Gresse
Hugo Gresse

Reputation: 17899

Group By Eloquent ORM

I was searching for making a GROUP BY name Eloquent ORM docs but I haven't find anything, neither on google.

Does anyone know if it's possible ? or should I use query builder ?

Upvotes: 33

Views: 180976

Answers (3)

chebaby
chebaby

Reputation: 7730

Laravel 5

WARNING: As @Usama stated in comments section, this groups by AFTER fetching data from the database. The grouping is not done by the database server.
I wouldn't recommend this solution for large data set.

This is working for me (i use laravel 5.6).

$collection = MyModel::all()->groupBy('column');

If you want to convert the collection to plain php array, you can use toArray()

$array = MyModel::all()->groupBy('column')->toArray();

Upvotes: 10

Aghnat Atqiya
Aghnat Atqiya

Reputation: 295

try: ->unique('column')

example:

$users = User::get()->unique('column');

Upvotes: 4

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Upvotes: 55

Related Questions