Skip to content
Advertisement

Split Eloquent collection into multiple arrays based on property name

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?

Advertisement

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());
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement