1

Can't Format created_at when use pluck.

VisitorsStatistic::where('landing_page_id', $this->landing_page->id)
         ->select('created_at', DB::raw('count(*) as visitors'))
         ->whereMonth('created_at', '>=', $this->start_month)
         ->whereMonth('created_at', '<=', $this->end_month)
         ->orderBy('created_at')
         ->groupBy('created_at')
         ->pluck('visitors','created_at')
         ->all();

I usually use the code below to group by date, but it doesn't work with pluck and give a strpos() error.

         //->groupBy(function($val) {
         //    return Carbon::parse($val->created_at)->format('d/m');
         //})

Is there a way to format date created_at when using pluck?

Aciddiz
  • 97
  • 9

1 Answers1

2

Give this a whirl:

VisitorsStatistic::where('landing_page_id', $this->landing_page->id)
         ->select(\DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d') AS created_at"), \DB::raw('count(*) as visitors'))
         ->whereMonth('created_at', '>=', $this->start_month)
         ->whereMonth('created_at', '<=', $this->end_month)
         ->orderBy('created_at')
         ->groupBy('created_at')
         ->pluck('visitors','created_at')
         ->all();

The formatting for the date is in the DATE_FORMAT() function.

dazed-and-confused
  • 1,268
  • 1
  • 9
  • 16
  • nice you made me feel stupid, worked too much didn't though about simpler solution. – Aciddiz Mar 26 '21 at 19:19
  • 1
    Nah, you're not stupid. I looked this exact same thing with a different MySQL function just a couple months ago. We're all students always learning something new. Good luck – dazed-and-confused Mar 26 '21 at 19:20