Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get distinct values for non-key column fields in Laravel?

This might be quite easy but have no idea how to.

I have a table that can have repeated values for a particular non-key column field. How do I write a SQL query using Query Builder or Eloquent that will fetch rows with distinct values for that column?

Note that I am not fetching that column only, it is in conjunction with other column values, so distinct() might not really work. So that question basically can be how to specify the column that I want to be distinct in a query now that distinct() accepts no parameters?

like image 535
gthuo Avatar asked Aug 10 '14 12:08

gthuo


2 Answers

You should use groupby. In Query Builder you can do it this way:

$users = DB::table('users')             ->select('id','name', 'email')             ->groupBy('name')             ->get(); 
like image 82
Marcin Nabiałek Avatar answered Oct 12 '22 16:10

Marcin Nabiałek


In Eloquent you can also query like this:

$users = User::select('name')->distinct()->get();

like image 37
Pathros Avatar answered Oct 12 '22 15:10

Pathros