Wednesday, March 15, 2017

Get Last n Months Data Group by Week - Laravel

I am trying to get last 4 months data filtered by week in Laravel. This is code I currently have:

$analytics =
        Data::select([
            DB::raw('WEEK(p_date_time) AS week'),
            DB::raw('COUNT(id) AS count'),
        ])
            ->where('p_id', $p_id)
            ->where('p_date_time', '>=', Carbon::now()->subMonth(4))
            ->groupBy('week')
            ->orderBy('week')
            ->get()
            ->toArray();

This code gives me 52 results based on Data for 1 full year (As I am using WEEK). But I need around 17 results for the last 4 months.

I can make that happen by gathering of each day and then adding 7 days data as chunk for last 4 months, but how can I do it with query alone?

Thanks.



via Tanvir Sourov

Advertisement