Split Eloquent collection into multiple arrays based on property name

1.3k views Asked by At

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?

2

There are 2 answers

3
Rwd On BEST ANSWER

Assuming you're using Laravel >=5.4, one option would be to make use of Higher order messages with collections e.g.

$form_data->map->period->toArray()

This would mean you code would look something like:

$form_data = $this->getData($initial_date, $final_date, $product_list, $group);

$chart->labels($form_data->map->period->toArray());
$chart->dataset('My dataset', 'line', $form_data->map->amount->toArray());

Alternatively, (as mentioned in the comments) you could also use pluck:

$form_data = $this->getData($initial_date, $final_date, $product_list, $group);

$chart->labels($form_data->pluck('period')->toArray());
$chart->dataset('My dataset', 'line', $form_data->pluck('amount')->toArray());
1
IGP On

You could use data_get() if you want to do the same thing with less lines.

$form_data = $this->getData($initial_date, $final_date, $product_list, $group);

$chart->labels(data_get($form_data, '*.period');
$chart->dataset('My dataset', 'line', data_get($form_data, '*.amount'));

data_get($target, $key, $default = null) works with simple objects, arrays and even Collections and returns an array. It's been in the framework since 5.5 version.