Items count of Last 7 days in Laravel

Here is a simple way to implement the items count along with date in past 7 days. Of course you can change the date range.

Here is the code for laravel controller

            // $period  = Amount of days you want to fetch data for.
            // To change the days just change P40D with any other number of days like P{days}D and 
            // do corresponding in the sql query below by replacing 40 Days with other days.

            $period = new DatePeriod((new DateTime())->sub(new DateInterval('P7D')), new DateInterval('P1D'), new DateTime());
            $range = []; //variable to store all the date range from staring date to end date.
            $dbData = []; //variable to store the final expected output

            // Initialize all range with count 0
            foreach ($period as $date) {
                $range[$date->format("Y-m-d")] = 0;
            }
            // Fetch all data with in the staring and ending date.
            $data = DB::table('table_name')
                ->selectRaw('DATE(created_at) as time, count(*) as count')
                ->whereDate('created_at', '>=', date_sub(date_create(), date_interval_create_from_date_string("7 days")))
                ->whereDate('created_at', '<=', date_create())
                ->groupBy('time')
                ->get();

            // Once fetched, store the count values in the array.
            foreach ($data as $val) {
                $dbData[$val->time] = $val->count;
            }

            // Merge the two values
            $data = array_replace($range, $dbData);

            //return the result
            return $data;

And you will get output like this.

image.png

Thats it. Happy Coding !