paranoid
paranoid

Reputation: 7105

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 )

Upvotes: 114

Views: 255411

Answers (9)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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

UPDATE: For versions < 5.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');

Upvotes: 282

EduAvila
EduAvila

Reputation: 9

In Laravel 8 this works for me

$arr = SomeModel::where("field", value)->get()->toArray();

Upvotes: 1

Orici
Orici

Reputation: 431

A simple way to get an array with the model IDs from a collection:

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

Available since Laravel 5.5: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Collection.html#method_modelKeys

Upvotes: 6

aslamdoctor
aslamdoctor

Reputation: 3935

Although you have marked the Answer, This is a much simpler approach

App\User::pluck('id')->toArray()

Upvotes: 3

Mahmoud Abdelsattar
Mahmoud Abdelsattar

Reputation: 1431

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

Upvotes: 6

Mehmet B&#252;t&#252;n
Mehmet B&#252;t&#252;n

Reputation: 749

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

Upvotes: 6

George Rappel
George Rappel

Reputation: 7188

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.

Upvotes: 35

Radames E. Hernandez
Radames E. Hernandez

Reputation: 4425

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!

Upvotes: 7

Amir Bar
Amir Bar

Reputation: 3105

read about the lists() method

$test=test::select('id')->where('id' ,'>' ,0)->lists('id')->toArray()

Upvotes: 5

Related Questions