Eloquent ORM laravel 5 Get Array of ids - php

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 )

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

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.

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!

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

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

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

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

In Laravel 8 this works for me
$arr = SomeModel::where("field", value)->get()->toArray();

Related

Is it possible to generate associative array from laravel pluck()

ModalName::pluck('id')->toArray();
i want id to be associative array with certain defined key.
such as 'my_key'=>id in a pluck
First of all pluck() return you already an array so no need to call toArray().
Yes you can make it associative by passing another argument on pluck method. Like this
$plucked = $collection->pluck('name', 'product_id');
sample result
['prod-100' => 'Desk', 'prod-200' => 'Chair']
please see docs here source
so in your case
ModalName::all()->pluck('id', 'name'); // name = field in your table

Laravel 5.2 - Change Data Format get from Eloquent

I have a model like this-
$feature_project = FeatureProject::select('feature_id')
->where('project_id', $project->id)
->get();
And if I return it, I am getting a output like this-
[
{
"feature_id": 2
},
{
"feature_id": 4
},
{
"feature_id": 9
}
]
But I want t output like this-
[2,4,9]
So I need to convert the output.
But I am not finding a way without using for-each loop (make a temp array, push all elements to that array from current array with a for-each loop).
But I think there is more smart way than that in Laravel to do that.
I think Laravel Collection is used for this purpose.
You can call pluck() method on the query builder.
$feature_project = FeatureProject::select('feature_id')
->where('project_id', $project->id)
->pluck('feature_id'); // [2,4,9]
https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_lists
Alternatively, you can use PHP's array_column() function for raw arrays.
http://php.net/manual/en/function.array-column.php
In Laravel's collections, you can call a method called Flatten, which flattens a multi-dimensional collection into a single dimension.
https://laravel.com/docs/5.2/collections#method-flatten
$collection = collect(['name' => 'taylor', 'languages' => ['php', 'javascript']]);
$flattened = $collection->flatten();
$flattened->all();
// ['taylor', 'php', 'javascript'];
With a fairly flat object, it should return just the values.
Use pluck():
$feature_project = FeatureProject::where('project_id', $project->id)->pluck('feature_id');
An alternative way also will be helpful in some cases.
We can run raw queries inside select function.
Here is an example:
$feature_project = FeatureProject::select(DB::raw('GROUP_CONCAT("feature_id")))
->where('project_id', $project->id)
->get();
In DB::raw we can run mysql query with function and case same as mysql query.
You can use lists() and toArray() :
$feature_project=FeatureProject::where('project_id', $project->id)->lists('id')->toArray();
Hope this helps.

Laravel 5.2 - pluck() method returns array

I'm trying to upgrade my project L5.1 -> L5.2. In upgrade guide there's one thing which isn't clear for me:
The lists method on the Collection, query builder and Eloquent query
builder objects has been renamed to pluck. The method signature
remains the same.
That's ok, rename refactoting from lists() to pluck() isn't a problem. But what with useful pluck() method which was in L5.0 and L5.1?
From the 5.0 documentation:
Retrieving A Single Column From A Row
$name = DB::table('users')->where('name', 'John')->pluck('name');
What is the alternative for old pluck() method in L5.2?
UPDATE:
Example:
var_dump(DB::table('users')->where('id', 1)->pluck('id'));
L5.1:
// int(1)
L5.2:
// array(1) { [0]=> int(1) }
The current alternative for pluck() is value().
In Laravel 5.1+, you can use the value() instead of pluck.
To get first occurence, You can either use
DB::table('users')->value('name');
or use,
DB::table('users')->where('id', 1)->pluck('name')->first();
laravel pluck returns an array
if your query is:
$name = DB::table('users')->where('name', 'John')->pluck('name');
then the array is like this (key is the index of the item. auto incremented value):
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
but if you do like this:
$name = DB::table('users')->where('name', 'John')->pluck('name','id');
then the key is actual index in the database.
key||value
[
1 => "name1",
2 => "name2",
.
.
.
100 => "name100"
]
you can set any value as key.
I use laravel 7.x and I used this as a workaround:->get()->pluck('id')->toArray();
it gives back an array of ids [50,2,3] and this is the whole query I used:
$article_tags = DB::table('tags')
->join('taggables', function ($join) use ($id) {
$join->on('tags.id', '=', 'taggables.tag_id');
$join->where([
['taggable_id', '=', $id],
['taggable_type','=','article']
]);
})->select('tags.id')->get()->pluck('id')->toArray();
In the original example, why not use the select() method in your database query?
$name = DB::table('users')->where('name', 'John')->select("id");
This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...
Larvel 5.3: Specifying a Select Clause

Sorting List in Laravel

I am new to Laravel. I have a List that is being returned as an array in Blade
called personType, but the keys are all out of order.
I see the List being generated in the controller like this:
$personTypeList = PersonType::lists('per_type', 'id');
But this returns an array that is unsorted. I've tried ksort( $personTypeList) but it causes an error.
Anybody can shine a light on what I may be doing wrong?
how about adding an orderBy?
$personTypeList = PersonType::orderBy('per_type', 'desc')->lists('per_type', 'id');
You can use the method sort available when you are dealing with collections in laravel.
//will sort the collection by values, in ASC order.
$personTypeList = PersonType::lists('per_type', 'id') -> sort();
Hope this works for you.
You need to cast the collection to an Array.
$personTypeList = ['' => ''] + PersonType::lists('per_type', 'id')->toArray();

How to Select Certain Fields in Laravel Eloquent?

How to Do following Query in Laravel Eloquent?
SELECT catID, catName, imgPath FROM categories WHERE catType = "Root"
I have tried following
CategoryModel::where('catType', '=', 'Root')
->lists('catName', 'catID', 'imgPath');
but its return only two fields.
Array ( [7] => Category 1 )
lists() turns the resulting collection into an array with key value. You can only have two database columns in there. Otherwise you have to use select() but then you will get a collection of models not just an array.
$categories = CategoryModel::select('catID', 'catName', 'imgPath')
->where('catType', '=', 'Root')
->get();
Selecting multiple columns
CategoryModel::get(['catName', 'catID', 'imgPath']);
Works with Laravel 5.3 too!
If you want to get certain columns then You can use one of the two method get() or all()
but the syntax is different for both, get() method takes array as argument and all() method takes string or array both as argument:
Model::all('field1','field2') with string as arguments
CategoryModel::all('catName', 'catID', 'imgPath')->where('catType','Root');
Model::all(['field1','field2']) with array as arguments
CategoryModel::all(['catName', 'catID', 'imgPath'])->where('catType','Root');
Model::get(['field1','field2'])
CategoryModel::get(['catName', 'catID', 'imgPath'])->where('catType','Root');
CategoryModel::wherecatType('Root')
->pluck('catName', 'catID', 'imgPath');
From laravel version 5.3^ lists() is deprecated and function pluck() is used instead.
pluck() returns a collection and if you need a simple array just prepend ->toArray() to it.

Categories