How to Easily Fetch a Database Column with Pluck in Laravel

How to get any specific column values from database using Laravel Pluck method

Get perticular column from database using Pluck - Laravel

In this article we will learn how can we use Laravel helper method pluck and what are the benefits of using this .

Pluck Method :

Laravel pluck helper method is used to retrieve specific column values from a given collection . The pluck helper method is basically returns an object . We can use pluck helper method with both Laravel query builder and Eloquent ORM .

It retrieves only the specified columns instead of loading the whole columns from a table . We will learn how can we use pluck method with example like , we have a table names ' users ' and we need to fetch only id and name of the every user using both Query Builder and Eloquent ORM .

In this example we will be using postman app for testing purpose but you can also use your browser also for testing the output .

checkController.php :

Using Eloquent Method :

public function UserData()
    {
        $data = User::pluck('name');
        return $data;
    }

Output :

[
    "Kishan maharana",
    "Prof. Grace Shields",
    "Ms. Elyse Blanda II",
    "Georgette Mayer",
    "Ansley Gleason",
    "Maegan Schultz"
]

We can also use pluck helper method with where condition and with multiple parameter in pluck helper method also as we normal do .

public function UserData()
    {
        $data = User::where('id','<',4)->pluck('name','id');
        return $data;
    }

Output :

{
    "1": "Kishan maharana",
    "2": "Prof. Grace Shields",
    "3": "Ms. Elyse Blanda II"
}

Using Query Builder :

public function UserData()
    {
        $data = DB::table('users')->where('id','<',4)->pluck('name','id');
        return $data;
    }

Output :

{
    "1": "Kishan maharana",
    "2": "Prof. Grace Shields",
    "3": "Ms. Elyse Blanda II"
}

Checking Output Type :

public function UserData()
    {
        $data = DB::table('users')->where('id','<',4)->pluck('name','id');
        return gettype($data);
    }


Output :

object




Previous Post Next Post

Contact Form