Laravel 5.2 - pluck() method returns array - php

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

Related

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.

Filter an object in Laravel 4.1

I am very new to Laravel and php and i am facing an issue with a collection. The collection is generated in this way:
$users = $media->campaign->users;
Which return this data:
[{id: 1, name: "name", suspended: 0},{id: 2, name: "name2", suspended: 1}]
How can i filter this object in laravel 4.1 to get only the elements that have 0 as suspended?
Use array_filter(array $array[, callable $callback[, int $flag]]):
array_filter($users, function($value) {
return($value->suspended === 0);
});
Check more in Laravel 4.2 documentation, Taylor wrote there that filtering collections use array_filter function. Also you should can use $users = $users->filter(function($user) {}); method.
Also, thanks to #xAoc, you can use filtering on SQL query:
$users = $media->campaign
->users()
->where("suspended", "=", 0)
->get();
Since you're doing a direct "equals" comparison, Laravel's Collection has a where() method you can use. For example:
$users = $media->campaign->users;
$users->where('suspended', 0);
This is a good option if you already have the Collection. If, however, you have control over generating the Collection, it would be more beneficial to only get the actual data you're looking for. In this case, you can add the where clause to the SQL statement, so you will only retrieve the final records you want. For example:
$users = $media->campaign->users()->where('suspended', '=', 0);
NB: the where() method on the Collection and the where() method on the query builder have different signatures. The query builder lets you pass in an operator to use ('=', '>', '<', etc). The Collection only does a direct equals comparison. This trips up a lot of people.

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

Use an array in Laravel update query

I would like to push an array in Where Clause of Laravel Update Query.
Here is the update query.
DB::table('users')->where('id', 1)->update(array('votes' => 1));
Is it possible to use the query like below ??
$array_of_ids;
DB::table('users')->where($array_of_ids)->update(array('votes' => 1));
Thanks
Simply use whereIn:
$array_of_ids;
DB::table('users')->whereIn('id', $array_of_ids)->update(array('votes' => 1));
Please read the documentation carefully. In this case, all kinds of where statements are documented here: Query Builder - Selects
Try this query:
DB::table('users')->whereIn('id', $array_of_ids)->update(['votes' => 1]);
Using Model:
User::whereIn('id', $array_of_ids)->update(['votes' => 1]);
using the query builder: The query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated. You may constrain the update query using where clauses:
DB::table('users')
->where('id', 1)
->update(['votes' => 1]);

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