Get Last 7 Days Records From Database In Laravel

Hello artisan,

In this example, I will show you how to fetch last 7 days record records in laravel. I will use carbon to show you the way of fetching last 7 days record in laravel. If you don't know how to fetch last 7 days record using carbon in laravel then this example is for you.

Let assume we have a date column in our table and we have to fetch last 7 days record  from this table. How we can write this query to fetch. I will show you an eloquent query using carbon to fetch last 7 days record.

Sometimes we need to show that kind of data to make a report in our application. So Let's see the example query of last 7 days records. I will use whereBetween to fetch this last 7 days records in laravel.

Example code: 

Route::get('/', function (\Illuminate\Http\Request $request) {

   
    $data = Transaction::whereBetween('date', [
                \carbon\Carbon::now()->subdays(7)->format('Y-m-d'),
                \carbon\Carbon::now()->subday()->format('Y-m-d')
            ])->get();

});

 

Recommended: How to Get Last N Days Records in Laravel

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js