Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent ORM laravel 5 Get Array of ids

I'm using Eloquent ORM laravel 5.1, and I want to return an array of ids greater than 0, my model is called test.

I have tried :

$test=test::select('id')->where('id' ,'>' ,0)->get()->toarray();

It returns :

Array ( [0] => Array ( [id] => 1 ) [1] => Array ( [id] => 2 ) )

But I want the result to be in simple array like this:

Array ( 1,2 )
like image 243
paranoid Avatar asked Dec 16 '15 09:12

paranoid


3 Answers

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 use 'pluck()' instead)

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');
like image 64
Zakaria Acharki Avatar answered Nov 02 '22 03:11

Zakaria Acharki


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.

like image 34
George Avatar answered Nov 02 '22 03:11

George


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!

like image 26
Radames E. Hernandez Avatar answered Nov 02 '22 02:11

Radames E. Hernandez