How To Use Pluck In Laravel 9 Example

Hi Artisan,

In this Post i will Explain you how to Utilize pluck method in laravel 8 application. In this article how to utilize pluck function in laravel. We will learn how to Add 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.

Basically pluck() method define it can get value column and key use pluck method.pluck method to returned amassment single column or designate a custom key column following example.

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

Solution : 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 BlogController 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\Blog;

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

       dd($users);
    }
}

Output
array:4 [
    1 => "admin"
    2 => "pratik"
    3 => "kishan"
   ]

It will help you.....

Post a Comment