Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JoaoHamerski's avatar

Eloquent "groupBy' returning only the first of each group

Here is my query:

$pendencies = Payment::groupBy(DB::raw('DATE(created_at)'))
            ->select('*', DB::raw('count(*) as total'))
            ->orderBy('created_at', 'DESC');

        dd($pendencies->get());

I want to group by date, only the date, not time, so i used the mysql DATE() function to convert the created_at field to date format, but when returning data this is the result:

Illuminate\Database\Eloquent\Collection {#1308 ▼
  #items: array:6 [▼
    0 => App\Models\Payment {#1309 ▶}
    1 => App\Models\Payment {#1310 ▶}
    2 => App\Models\Payment {#1311 ▶}
    3 => App\Models\Payment {#1312 ▼
      #guarded: []
      #connection: "mysql"
      #table: "payments"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      +preventsLazyLoading: false
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:11 [▼
        "id" => 9
        "order_id" => 2
        "payment_via_id" => 1
        "value" => 10.0
        "date" => "2021-07-19"
        "note" => null
        "created_at" => "2021-07-19 16:45:16"
        "updated_at" => "2021-07-19 16:46:13"
        "confirmed_at" => "2021-07-19"
        "is_confirmed" => 1
        "total" => 18
      ]
      #original: array:11 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #enableLoggingModelsEvents: true
      #oldAttributes: []
    }
    4 => App\Models\Payment {#1313 ▶}
    5 => App\Models\Payment {#1314 ▶}
  ]
}

As you can see it return the total of the groupBy but only the first eloquent model, what am i doing wrong?

0 likes
1 reply

Please or to participate in this conversation.