Ad

Laravel API, MySQL Query, Get Average Data In Same Date

- 1 answer

My table is about weight. For example,

(February 10, 2020) = 60kg
(February 11, 2020) = 62kg
(February 11, 2020) = 63kg
(February 11, 2020) = 64kg
(February 12, 2020) = 65kg

Json should return,

{
"weight": 60,
 "created_at": "2020-02-10"
},
{
"weight": 63,
"created_at": "2020-02-11"
},
{
"weight": 65,
"created_at": "2020-02-12"
}

with pagination.

Here's my existing code without average.

public function weightChart(Request $request, $id)
    {
        $data = WeightHistory::where('user_id', $id)->orderBy('created_at', 'DESC')->paginate(7);


        return WeightChartResource::collection($data);
    }
Ad

Answer

Change your query

$data = WeightHistory::where('user_id', $id)->orderBy('created_at', 'DESC')->paginate(7);

To

$data = WeightHistory::where('user_id', $id)->select('created_at', DB::raw('AVG(weight) as weight'))->groupBy('created_at')->orderBy('created_at', 'DESC')->paginate(7);
Ad
source: stackoverflow.com
Ad