Cant understand Eloquent distinct

Published 5 months ago by alexMafus

Hi i have a function that filter my users and now i want to show me unique users by first name but when i use this code show me only the first name how to filter unique users by first name and to show all of user data here is my code

 })->when($search_status, function ($query) use ($search_status) {
            return $query->select('first_name')->distinct();

If you return all the fields the records will no longer be unique.

Distinct only combines records where all the selected fields match.

This makes sense as how would it know which values to use for the other fields?

Say you have a "John Doe" and a "John Smith". Both have the same first name but what would the last name be for the record? Because they are different a "SELECT DISTINCT" query would return them both unless you only were pulling the first name column.

What are you trying to accomplish with your query? There likely is a different way to get the data you need.

5 months ago (252,680 XP)

It in a way doesn't make sense to do first names only like @spekkionu said:

Say you have a "John Doe" and a "John Smith".

But he basic distinct is:


You probably need to get at least first and last name. I rarely need distinct.

Look at this best answer:

You can have many clauses and conditions in eloquent or query builder.

But id would be even better with an order by first name then last name..


@alexMafus Eloquent distinct is same as mysql distinct, distinct will unique the row when all coulmns r equal, first checkout what mysql distinct do.

5 months ago (1,044,305 XP)

If you just want to know all the first_names so that you can list them in a dropdown for instance, then;


will give you a list of all the firstnames in the database

If, on the otherhand, the user has already selected 'john' from the dropdown (or keyed it) and now you want to list all the Johns ("and to show all of user data") then its a simple where that is required

$users = User::where('first_name',$first_name)->get();
5 months ago (1,044,305 XP)

sorry, doesnt make any sense to me?


@alexMafus The reason you are seeing 5 john doe is those 5 rows have different value is different column, there might be a two john doe as different person, distinct only works if all the coulmns are equal with another row...


so how can i have a functionality to not show all the players with same first name and last name but only one for example in JS i can filter the players how in eloquent ca i do that? @Snapey i just dont want to show duplicate players by first and last name (i try all day but i am new in laravel and cant do it).


2 differents players can having the same first and last name and not being the same person. Just a namesake.

Please sign in or create an account to participate in this conversation.