charles
charles

Reputation: 384

How to get datas by month? Laravel Eloquent

Using the created_at column, I want to retrieve data(s) in one query:


Expected returned values should:

$data: [
    1 : [
        //datas for january
    ],

    2 : [
        //datas for february
    ],

    //etc.
]


I tried this query:

$data = User::query()
    ->whereYear('created_at', now()->year - 1)
    ->get(function ($q){
        return groupBy(function ($q){
            return Carbon::parse($q->created_at)->format('m');
        });
    });

But I receive this error:

stripos() expects parameter 1 to be string, object given

Can someone could help me the proper querying for this?

Upvotes: 1

Views: 913

Answers (2)

Salim Djerbouh
Salim Djerbouh

Reputation: 11034

The nested closure functions with same variable names are very confusing, you can simplify things here

Call the groupBy method on the collection after get instead of the builder which only accepts a column name apparently

$data = User::query()
            ->whereYear('created_at', now()->year - 1)
            ->get()
            ->groupBy(function ($q) {
                return Carbon::parse($q->created_at)->format('m');
            });

See Docs

Upvotes: 2

Ahmed Atoui
Ahmed Atoui

Reputation: 1556

you should use sql method MONTH() to extract month from date then use groubby .like this :

 User::query()->select('created_at',  DB::raw('MONTH(created_at) month'))
->whereYear('created_at', now()->subYear())
->groupby('month')
->get();

Upvotes: 0

Related Questions