How to get 7 days Data / Record from Database in Laravel
In this article we will see how to get 7 days of data or record from database in Laravel 6/7/8 using Carbon.
We will take an example where i will retrieve last 7 days of record from users table from my database . In this example i am only showing you to retrieve last 7 days of data from Database but you can retrieve data of Last N number of days.
We will take two examples and try to get the last 7 days of data in two different way using whereBetween and where clause of Laravel .
Method 1 - Using whereBetween clause :
In this method we will use whereBetween clause of Laravel . This method takes two parameter first one is the column name and another one is as array containing start date and end date as shown in the following example .
public function lastNDaysData() { $start_date = Carbon::now()->subdays(7)->toDateTimeString(); $end_date = Carbon::now()->toDateTimeString(); $data = User::whereBetween('created_at',[$start_date,$end_date]) ->get(); dd($data); }
Method 2 - Using where clause :
In this method we will use where clause of Laravel to get Last 7 days or N days of data as shown in the below example .
public function lastNDaysData() { $date = Carbon::now()->subdays(7)->toDateTimeString(); $data = User::where('created_at','>',$date) ->get(); dd($data); }
Thank you for reading this article 😊
For any query do not hesitate to comment 💬