In this short guide, you will learn How to Get the Last 1 Month Data, Last 3 Months Data and Last 6 Months Data in Laravel.
First, we cover how to get the last 1 month data then last 3 months data and in the end we will cover how to get 6 months data in laravel.
Let’s get started.
Table of Contents
Assumption:
Let’s suppose we have a users
table, and we need to get the users who have joined in the last 3 months and 6 months respectively.
Here is the model structure of the User
Model:
class User extends Authenticatable
{
use HasFactory, Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
...
Here is the table columns:
How to get the last 1 month data in laravel?
So to get all the Users
which joined last month, We will using wherebetween
with created_at
column for the User
Model.
$users= User::select('*')
->whereBetween('created_at',
[Carbon::now()->subMonth(1), Carbon::now()]
)
->get();
The above code will give us all the users which have joined last month.
How to get the last 3 months data in laravel?
In the controller function, we will write the laravel eloquent query on the User
Model with the wherebetween
function on the created_at
column.
$users= User::select('*')
->whereBetween('created_at',
[Carbon::now()->subMonth(3), Carbon::now()]
)
->get();
This will give us all the users who have joined as in the last 1 month.
How to get the last 6 months data in laravel?
Same as the above code for the 3 months, just instead of 3 we need to get 6 months data of user.
$users= User::select('*')
->whereBetween('created_at',
[Carbon::now()->subMonth(6), Carbon::now()]
)
->get();
Conclusion:
Hope you have learned today on How to get 3 or 6 months previous data in laravel.
Let me know if you have any questions in the comments.
See you in the next one.
Write a Reply or Comment