Laravel Carbon subtract days from current date

PhpLaravelDatetimePhp Carbon

Php Problem Overview


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 ?

Php Solutions


Solution 1 - Php

Use subDays() method:

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

Solution 2 - Php

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();

Solution 3 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncosmolocView Question on Stackoverflow
Solution 1 - PhpAlexey MezeninView Answer on Stackoverflow
Solution 2 - PhpChris KelkerView Answer on Stackoverflow
Solution 3 - PhpJoskfgView Answer on Stackoverflow