What is the distinct() method in Laravel?
Overview
In Laravel, the distinct() method is used to fetch distinct records from the database, it is also part of Laravel query builder, which means it can be chained to other query builder methods as well.
The typical usage of this method is to find how many users made comments on a post. Since users can make more than one comment, it can be helpful to get the distinct number of users that commented.
Syntax
$users = DB::table('tablename')->distinct()->get();
Parameters
This method does not take any parameters.
Example
The yourController.php file shows how the distinct() method is used. To see the result, click on the “Output” tab in the executable code below.
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:y/pKeSS3Dw2DF8SSju5xWAZ0BNvTWnit4coXi271A/U=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=educative1
DB_USERNAME=user
DB_PASSWORD=user
BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"Demonstration of the distinct() method
Explanation
- In the example above, we try to fetch only distinct users from the
userstable. - In line 17, we chain the
distinct()method to thetable()method. Next, we use theget()method to retrieve the results of the query. We print all the distinct emails in the table as output.