Laravel 9 Pluck Method Example

Websolutionstuff | Jul-20-2022 | Categories : Laravel

In this article, we will see laravel 9 pluck method example. The pluck method retrieves all of the values for a given key. You can also retrieve values from arrays and collections. You may also pluck keys and values using the pluck() method.

Also, you can get selected column records from the database using the pluck() method. You may also pluck multiple columns in laravel 9.

So, let's see the pluck method in laravel.

Example 1: pluck using key

$collection = collect([
    ['id' => '1', 'name' => 'Laravel'],
    ['id' => '2', 'name' => 'PHP'],
]);
 
$plucked = $collection->pluck('name');
 
$plucked->all();
 
// ['Laravel', 'PHP']

 

 

Example 2: pluck collection

$plucked = $collection->pluck('name', 'id');
 
$plucked->all();
 
// ['1' => 'Laravel', '2' => 'PHP']

 

Example 3: pluck nested values

$collection = collect([
    [
        'id' => '1',
        'name' => [
            'car' => ['Audi Q5', 'Audi A8'],
        ],
    ],
    [
        'id' => '2',
        'name' => [
            'car' => ['Mercedes-Benz C-Class', 'Mercedes-Benz S-Class'],
        ],
    ],
]);
 
$plucked = $collection->pluck('name.car');
 
$plucked->all();
 
// [['Audi Q5', 'Audi A8'], ['Mercedes-Benz C-Class', 'Mercedes-Benz S-Class']]

 

 

Example 4: remove duplicate key

If duplicate keys exist, the last matching element will be inserted into the plucked collection.

$collection = collect([
    ['brand' => 'Tesla',  'color' => 'red'],
    ['brand' => 'Toyota', 'color' => 'white'],
    ['brand' => 'Tesla',  'color' => 'black'],
    ['brand' => 'Toyota', 'color' => 'grey'],
]);
 
$plucked = $collection->pluck('color', 'brand');
 
$plucked->all();
 
// ['Tesla' => 'black', 'Toyota' => 'grey']

 

Example 5: pluck data with model

public function index(){
   
   $names = Users::pluck('name', 'id');
   
   dd($names);
}
 
// ['1' => 'websolutionstuff', '2' => 'websolution']

 


You might also like:

Recommended Post
Featured Post
How To Convert PHP Array To JSON Object
How To Convert PHP Array To JS...

In this article, we will explore the process of converting a PHP array into a JSON object. We'll achieve this transf...

Read More

Jul-08-2020

Razorpay Payment Gateway Integration in Laravel 10 and VueJS 3
Razorpay Payment Gateway Integ...

In the rapidly advancing world of technology, the combination of Laravel 10 and VueJS 3 is unparalleled and exceptionall...

Read More

Aug-30-2023

How To Create Bar Chart In Laravel 9 Using Highcharts
How To Create Bar Chart In Lar...

In this article, we will see how to create a bar chart in laravel 9 using highcharts. A bar chart or bar graph is a...

Read More

Oct-05-2022

Laravel 11 Spatie Media Library Example
Laravel 11 Spatie Media Librar...

Hello, laravel web developers! In this article, we'll see how to install spatie media library in laravel 11. Here, w...

Read More

Jul-05-2024