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

ardf16's avatar

Universal (database) groupBy formatted date

Is there 'eloquent' solution for grouping results by formatted date that will not include having raw query like :

DB::raw("FORMAT(created_at, 'MM-yyyy') AS created_month")

which is not only ugly but also platform - specific.

I would like to make my application reusable on different environments without writting platform - specific code.

0 likes
5 replies
Sergiu17's avatar
User::get()->groupBy(function($q) {
    return $q->created_at->format('M-Y');
});
Tangente's avatar

I answered a question like this earlier

Try this method:

use Carbon\Carbon; $latest = Site::query() ->with('upvotes') ->orderBy('created_at', 'DESC') ->get() ->groupBy(function($date) { return Carbon::parse($date->created_at)->format('M'); // grouping by months

});

I would follow te same way as above

ardf16's avatar

Thanks for taking interest, @Sergiu17

My question is about formatting queries not working with data after fetching them.

Your reply is correct in most cases but in rare cases (especially resource considerate) selecting broad ranges of data and sorting them afterwards is just not a way to go.

So what's else on the table?

Sergiu17's avatar

@ARDF16 - Not sure if I understood you correctly, if so, then you can add a method to your model

class User extends Model
{
    public function getCreatedMonthAttribute()
    {
        return $this->created_at;
    }
}

// ....

$user = User::first();
$user->created_month;
ardf16's avatar

The issue here is that in order to fetch grouped by formated date columns directly from database you are forced to use raw queries which are database specific.

I'm looking for solution that uses eloquent query builder build in functions instead.

Please or to participate in this conversation.