Laravel Eloquent get results grouped by days Laravel Eloquent get results grouped by days laravel laravel

Laravel Eloquent get results grouped by days


I believe I have found a solution to this, the key is the DATE() function in mysql, which converts a DateTime into just Date:

DB::table('page_views')      ->select(DB::raw('DATE(created_at) as date'), DB::raw('count(*) as views'))      ->groupBy('date')      ->get();

However, this is not really an Laravel Eloquent solution, since this is a raw query.The following is what I came up with in Eloquent-ish syntax. The first where clause uses carbon dates to compare.

$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())                            ->groupBy('date')                            ->orderBy('date', 'DESC')                            ->get(array(                                DB::raw('Date(created_at) as date'),                                DB::raw('COUNT(*) as "views"')                            ));


You can use Carbon (integrated in Laravel)

// Carbonuse Carbon\Carbon;   $visitorTraffic = PageView::select('id', 'title', 'created_at')    ->get()    ->groupBy(function($date) {        return Carbon::parse($date->created_at)->format('Y'); // grouping by years        //return Carbon::parse($date->created_at)->format('m'); // grouping by months    });


Here is how I do it. A short example, but made my query much more manageable

$visitorTraffic = PageView::where('created_at', '>=', \Carbon\Carbon::now->subMonth())                        ->groupBy(DB::raw('Date(created_at)'))                        ->orderBy('created_at', 'DESC')->get();