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?
You should use groupby
. In Query Builder you can do it this way:
$users = DB::table('users') ->select('id','name', 'email') ->groupBy('name') ->get();
In Eloquent you can also query like this:
$users = User::select('name')->distinct()->get();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With