I'm using Eloquent ORM laravel 5.1, i want to return an array of ids greater than 0, My model called test
.
I have tried :
$test=test::select('id')->where('id' ,'>' ,0)->get()->toarray();
It return :
Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) )
But i want result to be in simple array like :
Array ( 1,2 )
You could use lists()
:
test::where('id' ,'>' ,0)->lists('id')->toArray();
NOTE : Better if you define your models in Studly Case
format, e.g Test
.
You could also use get()
:
test::where('id' ,'>' ,0)->get('id');
UPDATE: (For versions >= 5.2)
The lists()
method was deprecated in the new versions >= 5.2
, now you could use pluck()
method instead :
test::where('id' ,'>' ,0)->pluck('id')->toArray();
read about the lists() method
$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
From a collection, another way you could do it would be:
$collection->pluck('id')->toArray()
This will return an indexed array, perfectly usable by laravel in a whereIn query, for instance.
The correct answer to that is the method lists
, it's very simple like this:
$test=test::select('id')->where('id' ,'>' ,0)->lists('id');
Regards!
You may also use all() method to get array of selected attributes.
$test=test::select('id')->where('id' ,'>' ,0)->all();
Regards