Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Carbon subtract days from current date

I am trying to extract objects from Model "Users" whose created_at date has been more than 30 days from today.

Carbon::now() ==> I want as ==> Carbon::now() - 30days

$users = Users::where('status_id', 'active')
               ->where( 'created_at', '<', Carbon::now())
               ->get();

How can this be achieved ?

like image 817
zeetit Avatar asked Dec 13 '16 13:12

zeetit


People also ask

How do you subtract Carbon Days?

You can subtract days on current date using carbon in laravel 6, laravel 7, laravel 8 and laravel 9 version. If you need to subtract day or more days in date then you can use carbon in laravel. carbon provide subDay() and subDays() method to add days on carbon date object.

What is the use of Carbon in Laravel?

The Carbon package can be used for many purposes, such as reading the current date and time, changing the default date and time format, finding the difference between two dates, converting the date and time from one timezone to another timezone, etc.


3 Answers

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();
like image 154
Alexey Mezenin Avatar answered Oct 18 '22 04:10

Alexey Mezenin


You can always use strtotime to minus the number of days from the current date:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();
like image 21
Chris Kelker Avatar answered Oct 18 '22 04:10

Chris Kelker


From Laravel 5.6 you can use whereDate:

$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))
       ->get();

You also have whereMonth / whereDay / whereYear / whereTime

like image 39
Joskfg Avatar answered Oct 18 '22 05:10

Joskfg