Laravel Pluck Method Example | Laravel Pluck() | Pluck in Laravel

    By: Manu
    2 years ago

    Laravel Pluck with example


    A short guide on laravel pluck with example. You will learn laravel pluck method by example. You will understand the concept of laravel db query pluck.

    In this simple example of laravel pluck query builder.

    I will show you when we use pluck() in laravel 6, laravel 7 and laravel 8. When ever you need to get all ids with titles or names in array for your select dropdown from database in laravel at that time we have to use pluck() of collection.

    let's see bellow example:


    /**
    
     * Show posts ids.
    
     */
    
    public function index(){
    
       
    
       $ids = Post::pluck('id');
    
      
    
       dd($ids);
    
    }
    

    This code will output list of ids in array

    array:[
        0 => 1,
        1 => 2,
        2 => 3
    ]
    


    Getting multiple values from Laravel pluck


    /**
    
     * Show post id and title;
    
     */
    
    public function index(){
    
       
    
       $posts = Post::pluck('id', 'title');
    
      
       dd($posts);
    
    }
    

    This will give us out as

    array:4 [
        1 => "Title 1",
        2 => "Title 2",
        3 => "Title 3"
      ]