Laravel Collection pluck method example

Sometimes, you may want only one column from the database as array. Laravel provides easy way to get single column value from database. Laravel collection pluck() method only returns the selected column. 

In this article, I will share you how you can use Laravel pluck() method.

When generating list or select dropdown from database, pluck() method helps a lot.

Suppose we have countries collection array as below.

$countries = collect([
    ['name' => 'Afghanistan', 'code' => 'AF'],
    ['name' => 'Albania', 'code' => 'AL'],
    ['name' => 'Algeria', 'code' => 'DZ'],
    ['name' => 'Andorra', 'code' => 'AD'],
    ['name' => 'Angola', 'code' => 'AO']

Now we need only country name field. Let's take example below:

$country_name = $countries->pluck('name');

This will return only country name from the collection.


Now we can use this list in the blade view using foreach loop.

    @foreach ($country_name as $name)
        <li>{{ $name }}</li>

Now suppose we want to generate select dropdown with key and value pair. We can get this by passing second parameter as key field.

$country_name = $countries->pluck('name', 'code');

This will return name and code key-value pair.

    "AF" => "Afghanistan",
    "AL" => "Albania",
    "DZ" => "Algeria",
    "AD" => "Andorra",
    "AO" => "Angola"

Now you can simply loop through array into dropdown like this:

<select name="country">
    @foreach ($country_name as $key => $name)
        <option value="{{ $key }}">{{ $name }}</option>

This way, you can use Laravel collection pluck() method. I hope you liked this article.