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');
// ['Laravel', 'PHP']



Example 2: pluck collection

$plucked = $collection->pluck('name', 'id');
// ['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('');
// [['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');
// ['Tesla' => 'black', 'Toyota' => 'grey']


Example 5: pluck data with model

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


You might also like:

Recommended Post
Featured Post
How to Install and Configure Elasticsearch on Ubuntu
How to Install and Configure E...

Hey there! Today, I'm going to walk you through the process of installing and setting up Elasticsearch on your Ubunt...

Read More


Laravel 9 Create Zip File And Download
Laravel 9 Create Zip File And...

In this article, we will see laravel 9 create a zip file and download it. Laravel provides ZipArchive class fo...

Read More


How To Generate QRcode In Laravel
How To Generate QRcode In Lara...

In this example, I will give information about how to generate QR code in laravel. As per the current trend, many w...

Read More


Laravel 6/7 CRUD tutorial with example
Laravel 6/7 CRUD tutorial with...

In this example, I will show you how to make simple laravel CRUD(insert, update, delete, or list) operations with e...

Read More