Eloquent ORM laravel 5 Get Array of ids

paranoid picture paranoid · Dec 16, 2015 · Viewed 138.9k times · Source

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 )

Answer

Zakaria Acharki picture Zakaria Acharki · Dec 16, 2015

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();

NOTE: If you need a string, for example in a blade, you can use function without the toArray() part, like:

test::where('id' ,'>' ,0)->pluck('id');