I'm creating a graph using Laravel Charts and I'm getting the columns (time periods) and the dataset from an Eloquent query.
My query returns an array like the following:
Period | Amount |
---|---|
01/21 | 200.00 |
02/21 | 150.00 |
03/21 | 175.00 |
... | ... |
Laravel Charts require you to input an array for the chart label and an array for the chart values. Currently, I create and populate the arrays in this manner:
//the function getData returns the table above as an Eloquent Collection
$form_data = $this->getData($initial_date, $final_date, $product_list, $group);
$labels = [];
$dataset = [];
foreach ($form_data as $data) {
array_push($labels, $data->period);
array_push($dataset, $data->amount);
}
$chart->labels($labels);
$chart->dataset('My dataset', 'line', $dataset);
Is there a "more native" way of doing this?
Assuming you're using Laravel >=5.4, one option would be to make use of Higher order messages with collections e.g.
This would mean you code would look something like:
Alternatively, (as mentioned in the comments) you could also use pluck: