Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 - pluck() method returns array

I'm trying to upgrade my project L5.1 -> L5.2. In upgrade guide there's one thing which isn't clear for me:

The lists method on the Collection, query builder and Eloquent query builder objects has been renamed to pluck. The method signature remains the same.

That's ok, rename refactoting from lists() to pluck() isn't a problem. But what with useful pluck() method which was in L5.0 and L5.1?

From the 5.0 documentation:

Retrieving A Single Column From A Row

$name = DB::table('users')->where('name', 'John')->pluck('name');

What is the alternative for old pluck() method in L5.2?

UPDATE:

Example:

var_dump(DB::table('users')->where('id', 1)->pluck('id'));

L5.1:

// int(1)

L5.2:

// array(1) { [0]=> int(1) }
like image 988
Limon Monte Avatar asked Dec 21 '15 22:12

Limon Monte


4 Answers

The current alternative for pluck() is value().

like image 190
user1669496 Avatar answered Nov 09 '22 20:11

user1669496


laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

like image 44
NuOne Avatar answered Nov 09 '22 21:11

NuOne


In Laravel 5.1+, you can use the value() instead of pluck.

To get first occurence, You can either use

DB::table('users')->value('name');

or use,

DB::table('users')->where('id', 1)->pluck('name')->first();
like image 20
reshma Avatar answered Nov 09 '22 19:11

reshma


I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();

it gives back an array of ids [50,2,3] and this is the whole query I used:

   $article_tags = DB::table('tags')
    ->join('taggables', function ($join) use ($id) {
        $join->on('tags.id', '=', 'taggables.tag_id');
        $join->where([
            ['taggable_id', '=', $id],
            ['taggable_type','=','article']
        ]);
    })->select('tags.id')->get()->pluck('id')->toArray();
like image 13
Furqan S. Mahmoud Avatar answered Nov 09 '22 21:11

Furqan S. Mahmoud