To achieve the desired result, you can use the Laravel collection's groupBy method to group the related models by their "measured_at" date. Here's an updated version of the GetCustomerBodySize method that should work:
public function GetCustomerBodySize($customerId, $month, $year)
{
$customerUserId = Customer::findOrFail($customerId)['user'];
$bodySizes = CustomerBodySize::with(['customer_data.user_body_sizes.body_parts'])
->whereRelation('customer_data', 'id', $customerUserId)
->whereMonth('measured_at', '=', $month)
->whereYear('measured_at', '=', $year)
->orderBy('measured_at')
->get()
->groupBy('measured_at')
->values()
->map(function ($group) {
return $group->map(function ($item) {
return $item->customer_data->user_body_sizes;
});
});
return $bodySizes->isEmpty() ? null : $bodySizes->first();
}
Here's what's happening in the updated code:
- We're using the groupBy method to group the related models by their "measured_at" date.
- We're using the values method to remove the keys from the resulting collection.
- We're using the map method to transform each group into an array of user_body_sizes models.
- We're returning the first group, or null if the collection is empty.
Note that we're using the get method instead of first to retrieve all the related models, since we need to group them before returning the result.