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 usin
$users = User::select('column1', 'column2', 'column3')->distinct()->get();
retrieves all three coulmns for distinct rows in the table. You can add as many columns as you wish.
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 use this
$users = User::select('name')->groupBy('name')->get()->toArray() ;
groupBy is actually fetching the distinct values, in fact the groupBy will categorize the same values, so that we can use aggregate functions on them. but in this scenario we have no aggregate functions, we are just selecting the value which will cause the result to have distinct values
I found this method working quite well (for me) to produce a flat array of unique values:
$uniqueNames = User::select('name')->distinct()->pluck('name')->toArray();
If you ran ->toSql()
on this query builder, you will see it generates a query like this:
select distinct `name` from `users`
The ->pluck()
is handled by illuminate\collection lib (not via sql query).
Note that groupBy
as used above won't work for postgres.
Using distinct
is probably a better option - e.g.
$users = User::query()->distinct()->get();
If you use query
you can select all the columns as requested.
$users = Users::all()->unique('name');