Result query to single array of string - php

I would like to transform the result of an Eloquent query into a single array of strings.
What my query currently gives:
(I apply a ->toArray() to initial query to get that :)
array:2 [▼
0 => array:1 [▼
"title" => "User"
]
1 => array:1 [▼
"title" => "Premium"
]
]
What I would like it to give me:
['User', 'Premium'];
My query :
Rank::where('strength', '<', $this->rank->strength)->select('title')->get();
Thanks in advance

You can use pluck():
Rank::where('strength', '<', $this->rank->strength)->pluck('title');

If you want exactly same array response instead of collection, You can add toArray() function at the last
$ranks = Rank::where('strength', '<', $this->rank->strength)
->pluck('title')->toArray();

Related

Get the top value of array

Context: To give context, I am trying to create a graph with the months as the labels and the number of applications as the dataset.
My code:
$apps = Application::whereBetween('created_at', [
Carbon::now()->startOfYear(),
Carbon::now()->endOfYear(),
])
->get()
->groupBy(function ($val) {
return Carbon::parse($val->created_at)->format('M');
})
->toArray();
returns
array:3 [▼
"Jan" => array:2 [▶]
"Feb" => array:1 [▶]
"May" => array:1 [▶]
]
I want to create an array that produces this result:
['Jan', 'Feb', 'May']
I have tried using array keys, values, etc without any joy.
If you are looking for only month list then you can use selectRaw and groupBy in query
$apps = Application::whereBetween('created_at', [
Carbon::now()->startOfYear(),
Carbon::now()->endOfYear(),
])->selectRaw('MONTHNAME(created_at) as month,count(*) as total')
->groupBy('month')
->pluck('total','month')->toArray();
For getting months and count list separately
array_keys($apps) and array_values($apps)

Laravel 5.8+get array of columns and rows from query

Relatively new to Laravel and trying to create a REST api that will have as a response a json that is split between rows and cols of a query
So, the code used to generate the json is:
$r = array(
'cols' => array_keys(get_object_vars(Dd_hr::take(2)->get())),
'rows' => Dd_hr::take(2)->get()
);
return response()->json($r, 201);
Basically, the json should look something like:
{"cols":[{"id", "user_name"}],"rows":[{"710206","user"}]}
But in fact it looks like:
{"cols":[],"rows":[{"id":"710206","user_name":"user"}]}
Could someone help me to solve this issue?
The result of dd(Dd_hr::take(2)->get()->toArray()):
array:2 [▼
0 => array:27 [▼
"rn" => "1"
"id" => "710206"
"user_name" => "user"
]
1 => array:27 [▼
"rn" => "2"
"id" => "710207"
"user_name" => "user"
]
]
Didn't find a way to do this properly so here goes the good old array_map.
This doesn't remove the "rn" key. If you want to chose the keys in the select you can, it'll even make creating the JSON easier since you'll already have the 'cols'.
$res_array = Dd_hr::take(2)->get()->toArray();
$cols = array_keys($res_array[0]);
$rows = array_map(function($row){
return array_values($row);
}, $res_array);
return response()->json(array('cols'=>$cols, 'rows'=>$rows), 201);
This returns :
"{"cols":["rn","id","user_name"],"row":[["1","710206","user"],["2","710207","user"]]}"

Laravel collection pluck dropping a value

I have the following Eloquent query in a Laravel 5.2 project:
$regsByCtryCollection = Organisation::join('countries_currencies', 'countries_currencies.id', '=', 'organisations.country_id')
->select(DB::raw('DISTINCT LCASE(countries_currencies.country_code) AS ctry, COUNT(organisations.id) AS val'))
->groupBy('ctry')
->get();
The raw query produces this output:
ctry val
at 1
au 5
br 1
The Eloquent call produces a collection of three rows (matching raw query output) like this:
Collection {#791 ▼
#items: array:3 [▼
0 => Organisation {#777 ▼
#table: "organisations"
#hidden: []
........
#attributes: array:2 [▶]
#original: array:2 [▼
"ctry" => "at"
"val" => 1
]
#relations: array:5 [▶]
........
}
1 => Organisation {#778 ▶}
2 => Organisation {#779 ▶}
]
}
I then pluck the values and format for Highmaps like this
$regsByCtry = $regsByCtryCollection->pluck('ctry', 'val')->map(function($country, $value) {
return [
"hc-key" => $country,
"value" => $value
];
})->values()->toJson();
And one of the values is dropped and I get this:
[
{"hc-key":"br","value":1},
{"hc-key":"au","value":5}
]
Why is the first entry getting dropped?
{"hc-key":"at","value":1}
I am using this same process with two other Eloquent queries and it works as expected, but just not on this collection.
Additionally, I also sum all the values in the array of objects like this:
$regsTotal = array_sum($regsByCtryCollection->pluck('val')->toArray());
And I get the correct value, including all three records summed:
$regsTotal = 7;
The issue is with pluck('ctry', 'val'). This will return val as key & ctry as value. In your query output at & br has same value 1. So one of it getting replaced by the other one.
Try pluck('val', 'ctry')->map(function($value, $country)
Reference

Laravel eloquent query with

This query returns all groups with an id however it also returns all the products to every group.
$groups = \App\Group::where('campaign_id', $id)->with('product')->get();
dd($groups->toArray());array:2 [▼
This is the output.
0 => array:6 [▼
"id" => 24
"campaign_id" => "TRE36934"
"group_name" => "group2"
"created_at" => "2017-05-17 16:14:55"
"updated_at" => null
"product" => array:4 [▼
0 => array:8 [▶]
1 => array:8 [▶]
2 => array:8 [▶]
3 => array:8 [▶]
I am trying to return the groups with same id. Can I somehow query? The join in the id in the groups table and the foreign key in call 'group' in the group table.
A simple inner join should suffice here, right?
$groups = \App\Group::join('product', 'group.campaign_id', '=', 'product.group')
->where('group.campaign_id', $id)
->get();
try :
$groups = Group::join('product', 'group.campaign_id', '=', 'product.group')
->where('group.campaign_id', $id)
->get();
If you want to get your product with the same campaing id, you can do the following :
$products = Product::get()->groupBy('campaign_id');
Or you can do it directly from SQL
So, if you want a collection of Product, use your product model :)
I'm not sure but you may try this:
$group = \App\Group::where('campaign_id', $id)->get();
$group->load('products');
Thanks for all your replies they all got me a bit cloer
$products = \App\Product::join('groups', 'groups.id', '=', 'products.group')->get()->groupBy('group');
The basic groupby by Mathieu Ferre got me close. I added a join with a groupby as suggested by Mozammil on the name to give me
$products = \App\Product::join('groups', 'groups.id', '=', 'products.group')->get()->groupBy('group_name');

Laravel (5.3) pluck collection is returning other results than array

I've encoutered something strange. I'm making a selectbox, and i'm using the pluck method on a database model.
This piece of code:
$orgs = Organisation::pluck('name', 'id');
dd($orgs);
Gives me the following results:
Collection {#611 ▼
#items: array:6961 [▼
0 => "Test organisatie"
1 => "Name"
2 => "Another"
As you can see, the ID is not present.
Now when i make it into an array:
$orgs = Organisation::pluck('name', 'id')->toArray();
dd($orgs);
It gives the following results:
array:6961 [▼
1 => "Test organisatie"
3 => "Name"
19 => "Another"
The array is perfectly usable, i just don't understand why there's a difference.
--Edit:
When i use the collection in the select form helper, it does display the keys properly. Making me think it's a bug in the var dumper?
#Patrick Vd Pols
could you please try as below
Organisation::pluck('name','id')->all();

Categories