How to retrieve a list of column values in Laravel

Overview

In some situations, we may require an attribute or column value from the fetched result, but not the whole row. We use the pluck() query builder in such cases.

What is the pluck() method?

The pluck() method is a Laravel query builder that returns an instance of Illuminate\Support\Collection. This instance contains the values of an attribute.

Syntax

$singleValue= DB::table('tableName')->pluck('ColumnName');

Parameters

The pluck() method receives one parameter:

  1. ColumnName: This is the column’s name whose values we want to retrieve.

Code example

The yourController.php file shows how the pluck() method is used. We will see the result in the “Output” tab, after executing the code given 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}"
Code example for the "pluck()" method

Code explanation

In the code example given above:

  • In line 5, we import the Illuminate\Support\Facades\DB class, which allows us to work with databases.

  • In line 17, we create a function called columnValue() that uses the pluck() method.

  • In line 18, we use the pluck() method to retrieve the values of the column named firstName in the table users. The table() query builder retrieves all the users on the database table.

  • The result we get from the query is a collection.

  • In lines 20–21, we loop through the collection with the foreach() method and also echo the firstName variable.

Output

Depending on the content of our database users table, the output should look like the output of the code sample given above. Please run the code sample above to get a feel of it.

It is just the plain text of firstName from our database users table.