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 )
shareimprove this question
 

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)

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

Using Pluck to extract certain values from a collection

Hope this helps.

shareimprove this answer
 
5 
Just to point out that lists method is now deprecated in 5.2. Use pluck instead. – Fahmi Jun 27 '16 at 0:50
   
just to another point out that camelCase is like this. so for "test" in camel case you should write "test" not "Test". – Hamid Naghipour Apr 17 at 19:58

read about the lists() method

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()
shareimprove this answer
 
   
when I use in_array_command in blade file show this error. >in_array() expects parameter 2 to be array, object given – paranoid Dec 16 '15 at 9:29
   
oh now I get you, you need to call toArray(), lists() return collection – Amir Bar Dec 16 '15 at 9:32

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!

shareimprove this answer
 

来自 https://stackoverflow.com/questions/34308169/eloquent-orm-laravel-5-get-array-of-ids