How can convert the result from eloquent to associative array. I need to select tow column and have one as key and another as value. Here is the closet I got, however the value is an array. I want it to be only "my_value" column.
$array = Post::select('my_key','my_value')->get()->keyBy('my_key')
You should use lists (Laravel 5.1) or pluck (Laravel 5.2+):
$array = Post::lists('my_value', 'my_key');
or
$array = Post::pluck('my_value', 'my_key');
I found a way to do so, I'm not sure whether it's proper way to do this performance wise though...
$array = Post::select('my_key','my_value')->get()->mapWithKeys(function ($item) {
return [$item['my_key'] => $item['my_value']];
})->toArray();
Related
I have a field called language in my table submission. Here the different user has submitted their problem with different language such as java(56) 5 times, CPP(45) 7 times, and python(71) 10 times.
I want to have a query in laravel with eloquent such that it returns an array or with key-value pair as
$user_lang = ['56'=>5,'45'=>7,'71'=>10]
here 56,45,71 are the id of the languages
If you have prepared data like count of how many times, you can simply use pluck method. eg
$user_lang = Language::where(<condition>)->pluck('times', 'id');
It will return the array as you desired.
If you do not have prepared count, then count it using group by and simply use same pluck method .
$result = Submission::selectRaw('id', 'COUNT(DISTINCT id) AS times'))
->groupBy(id)
->get();
$user_lang = [];
$result->map($result, function($item){
$user_lang[$item->id] = $item->times;
});
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
db column screenshot
I want to fetch only two columns data from table 1st column data as array key and another column data as array value.
as array['wid'=>'temp']
result should be array['1'=>'1.5','2'=>'11.50']
for laravel 5.4
You could use the pluck() method (scroll down to the Retrieving A List Of Column Values) e.g.
$data = DB::table('city_list')->pluck('city_name', 'cid');
Use Collection pluck() The pluck method retrieves all of the values for a given key:
$data = DB::table('city_list')->pluck('city_name','cid');
For more information visit laravel doc here
This worked for me.
$data = DB::table('city_list')->select('cid','city_name')->get();
$val = array();
foreach ($data as $key => $value) {
$val[$value->cid]=$value->city_name;
}
I don't get this, I have a collection of items.
The collection contains in this case one and only one item at index 1 as it was filtered from a bigger collection.
The point is how do I get the only piece of data I need without having to reset the values of the index and then accessing at index 0 ??
This is a case where I will always have only ONE item in the collection but the index at could be different so I can't use the [0] index by default.
//returns all items with 'item_color_id" = 1
$item = Item::where(//some constraints);
$filtered = $item->filter(function ($i) {
return $i->item_color_id == 1;
});
if (count($filtered)) {
//need to access a single data inside the collection
// like for example 'item_brand_id'
//I can do it like this:
$filtered = $filtered->values();
$item_brand_id = $filtered[0]['item_brand_id'];
//but what sense does it have?? how can we access 'item_brand_id'
//from $filtered without resetting the indexes?
}
it doesn't make any sense to me that we don't have a method to access the data directly, or if we have it I missed it.
For example I coould use max() or min() on $filtered like this:
$max_brand_id = $filtered->max('item_brand_id');
It doesn't make any sense to find the max id in this case I know, but it shows that we can find the data in one passage.
I tried only('item_brand_id); but that returns empty while the data is there.
You still have eloquent collection so you can do just call first() function
$item_brand_id = $filtered->first()->item_brand_id;
filter() is used when you want a collection of matching elements, even if that only results in one element.
If you know that you only want one element that matches a truth test, use first() instead. It has the same signature.
Item::where(...)->get()->first(function ($item) {
return $item->item_color_id == 1;
})->get('item_brand_id');
You could change your database query to just return one element. If the result is always just one, there is no need to load an entire collection.
$item = Item::where(/*some constraints*/)->where('item_color_id', 1)->first();
if (isset($item))
echo $item->item_brand_id;
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.