How To Use Pluck In Laravel?


Share:
Published By: Admin, Published On: Jun 25, 2021, Category: Laravel 8 Laravel

Hi Guys,

Today, in this tutorial i will share you how to use pluck method in laravel 8 application. In this article how to use pluck function in laravel. We will learn how to integrate two method get and post in laravel 8.

How Does Laravel pluck() Work?

The Laravel pluck () as the denomination suggests, extracts certain values, as suggested. It literally plucks the information out from the given array and engenders it as an output. However, it is most efficacious against objectives, but will work well against arrays additionally.

So, pluck() it can get value column and key utilizing pluck method.pluck method to returned amassment single column or designate a custom key column following example.

Basically, pluck method return a column value using key.pluck method to return a collection single column value.

Now let's see bellow full example how to use pluck in laravel 8. So let's follow bellow step by step:

Example : 1

Here,In this first example i will explain single for the returned collection.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(){
       
       $ids = \DB::table('users')->pluck('id');

       dd($ids);
    }
}

Output
array:[
    0 => 1
    1 => 2
    2 => 3
   ]
Example : 2

Next,In this second example i will give you specify a custom key column for the return collection.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(){
       
       $users = User::pluck('name','id');

       dd($users);
    }
}

Output
array:4 [
    1 => "admin"
    2 => "bhavesh"
    3 => "dharmik"
   ]

It will help you.....

Share: