You can retrieve distinct field values of documents in a collection by
calling the distinct() method on an object collection or a query
builder.
To retrieve distinct field values, pass a query filter to the
where() method and a field name to the select() method. Then,
call distinct() to return the unique values of the selected field in
documents that match the query filter.
Tip
For more information about query filters, see the Retrieve Documents that Match a Query section of the Read Operations guide.
Example
Select from the following Eloquent and Query Builder tabs to view usage examples for the same operation that use each corresponding query syntax:
This example performs the following actions:
Uses the
MovieEloquent model to represent themoviescollection in thesample_mflixdatabaseRetrieves distinct field values of documents from the
moviescollection that match a query filterPrints the distinct values
The example calls the following methods on the Movie model:
where(): Matches documents in which the value of thedirectorsfield includes"Sofia Coppola"select(): Retrieves the matching documents'imdb.ratingfield valuesdistinct(): Retrieves the unique values of the selected field and returns the list of valuesget(): Retrieves the query results
$ratings = Movie::where('directors', 'Sofia Coppola') ->select('imdb.rating') ->distinct() ->get(); echo $ratings;
[[5.6],[6.4],[7.2],[7.8]]
This example performs the following actions:
Accesses the
moviescollection by calling thetable()method from theDBfacadeRetrieves distinct field values of documents from the
moviescollection that match a query filterPrints the distinct values
The example calls the following query builder methods:
where(): Matches documents in which the value of thedirectorsfield includes"Sofia Coppola"select(): Retrieves the matching documents'imdb.ratingfield valuesdistinct(): Retrieves the unique values of the selected field and returns the list of valuesget(): Retrieves the query results
$ratings = DB::table('movies') ->where('directors', 'Sofia Coppola') ->select('imdb.rating') ->distinct() ->get(); echo $ratings;
[5.6,6.4,7.2,7.8]
To learn how to edit your Laravel application to run the usage example, see the Usage Examples landing page.