Laravel - how to group a Date string on table using collection

59 views Asked by At

i want to group my date Month but i don't know how to do that. i try used groupBy() but its giving me a error

$user = Auth::user()->id;
$date = productSold::where('user_id',$user)->get();

$collect = collect($date)->map(function ($date) {
    return date('M',strtotime($date->created_at))->groupBy('created_at');
});
return $collect;

error : Call to a member function groupBy() on string

without groupby this is the output :

[
"Oct",
"Oct",
"Nov",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec",
"Dec"
]

i want to group "Oct", "Nov", "Dec"

1

There are 1 answers

3
Andre Haykal On

Its error because you group by it from a string. So you should take out groupBy statement from map function. So the result should be like :

$collect = collect($date)->map(function ($date) {
        return [
            "created_at" => date('M',strtotime($date->created_at))
        ];
    })->groupBy('created_at');

The result should be like this.