How to Get Last 3 or 6 Months Data in Laravel?

December 22, 2021
Laravel
How to Get Last 3 or 6 Months Data in Laravel?

In this short guide, you will learn How to Get the Last 3 Months Data and the Last 6 Months Data in Laravel.

First, we cover how to get the last 3 months data and we will cover how to get 6 months data in laravel.

how accurate is an hiv test after 3...
how accurate is an hiv test after 3 months (hiv testing)

Let’s get started.

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 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 3 months.

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

Your email address will not be published. Required fields are marked *


Icon