Coder Perfect

Subtract days from the current date with Laravel Carbon.

Problem

I’m trying to retrieve items from Model “Users” that have been generated more than 30 days ago.

Carbon::now() ==> I’d like it to be as ==> 30 days – Carbon::now()

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

What is the best way to accomplish this?

Asked by zeetit

Solution #1

Use subDays() method:

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

Answered by Alexey Mezenin

Solution #2

To subtract the amount of days from the current date, use strtotime:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();

Answered by Chris Kelker

Solution #3

You can use whereDate: since Laravel 5.6.

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

There’s also whereMonth/whereDay/whereYear/whereTime.

Answered by Joskfg

Post is based on https://stackoverflow.com/questions/41122265/laravel-carbon-subtract-days-from-current-date