search

Home  >  Q&A  >  body text

Laravel: filter and group based on created_at and sum costs

Based on the table below

I want to get all the records on the created_at column grouped by month and sum the cost month for each record.

Hope I can explain it.

P粉314915922P粉314915922446 days ago429

reply all(1)I'll reply

  • P粉868586032

    P粉8685860322023-09-10 21:01:52

    You can do this

    $monthlyCosts = DB::table('my_table')
                ->selectRaw("DATE_FORMAT(created_at, '%m-%Y') as month, SUM(cost) as total_cost")
                ->groupBy('month')
                ->get();

    reply
    0
  • Cancelreply