PHP

Retrieve Specific Column Values or Key-Value Pairs

Learn how to use Eloquent's `pluck` method to efficiently retrieve a list of column values or an associative array of key-value pairs from your database in Laravel.

use App\Models\Category;

// Retrieve a collection of all 'name' values from the categories table.
$categoryNames = Category::pluck('name');
/*
   $categoryNames would be something like:
   Illuminate\Support\Collection {# ...
     all: [
       "Electronics",
       "Books",
       "Clothing",
     ]
   }
*/

// Retrieve an associative array where 'id' is the key and 'name' is the value.
$categoriesMap = Category::pluck('name', 'id');
/*
   $categoriesMap would be something like:
   Illuminate\Support\Collection {# ...
     all: [
       1 => "Electronics",
       2 => "Books",
       3 => "Clothing",
     ]
   }
*/
How it works: The `pluck` method is used to retrieve a single column's values from the database, either as a simple numerically indexed collection or as an associative array. When passed a single argument, it returns a collection of values for that column. When passed two arguments, the first argument specifies the column whose values should be the collection's values, and the second argument specifies the column that should be used as the collection's keys. This is particularly useful for populating dropdown menus or creating lookup maps.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs