phplaraveldate-formattingpluck

Laravel pluck, groupBy custom date Format


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?


Solution

  • 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.