John Davidson

php - Split Eloquent collection into multiple arrays based on property name

0 comments
Message:


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
... ...


My Answer:
To split the Eloquent collection into multiple arrays based on the property name, you can use the `groupBy` method provided by Laravel collections. Here's an example of how you can achieve this:

php
// Assuming $data is the Eloquent collection returned from your query
$data = YourModel::all();

// Group the collection by the period
$groupedData = $data->groupBy('period');

// Initialize an empty array to store the final result
$result = [];

// Loop through the grouped data and format it into arrays
foreach ($groupedData as $period => $items) {
$amounts = $items->pluck('amount')->toArray();
$result[] = [
'period' => $period,
'amounts' => $amounts
];
}

// Now $result will contain an array of arrays, each containing the period and corresponding amounts


You can then use the `$result` array to create your graph using Laravel Charts.

Rate this post

4 of 5 based on 2213 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us