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 )
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!
read about the lists() method
$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
Although you have marked the Answer, This is a much simpler approach
App\User::pluck('id')->toArray()
Just an extra info, if you are using DB
:
DB::table('test')->where('id', '>', 0)->pluck('id')->toArray();
And if using Eloquent model:
test::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.
You can use all()
method instead of toArray()
method (see more: laravel documentation):
test::where('id' ,'>' ,0)->pluck('id')->all(); //returns array
If you need a string
, you can use without toArray()
attachment:
test::where('id' ,'>' ,0)->pluck('id'); //returns string
You may also use all() method to get array of selected attributes.
$test=test::select('id')->where('id' ,'>' ,0)->all();
Regards
Source: Stackoverflow.com