Search code examples
laraveleloquentbuilder

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?


Solution

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

    $users = DB::table('users')
                ->select('id','name', 'email')
                ->groupBy('name')
                ->get();