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:

JavaScript

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.

JavaScript

This would mean you code would look something like:

JavaScript

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

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement