Your Guide to Fetching 1 Year of Database Records in Laravel

How to get 1 year Data / Record from Database in Laravel

Your-Guide-to-Fetching-1-Year-of-Database-Records-in-Laravel

In this article we will see how to get 1 year of data or record from database in Laravel 6/7/8 using Carbon.
We will take an example where i will retrieve last 1 year of record from users table from my database . In this example i am only showing you to retrieve last 1 year of data from Database but you can retrieve data of Last N number of years. 

We will take two examples and try to get the last 1 year 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 lastNYearsData()
{ $start_date = Carbon::now()->subYears(1)->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 1 year or N years of data as shown in the below example .

public function lastNYearsData()
    {
    	$date = Carbon::now()->subYears(1)->toDateTimeString();
    	
    	$data = User::where('created_at','>',$date)
    				->get();
    	dd($data);
    }



Previous Post Next Post

Contact Form