145

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 ?

5 Answers 5

305

Use subDays() method:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();
Sign up to request clarification or add additional context in comments.

9 Comments

Are you sure about changing '<' to '>' for getting users created more than 30 days ago?
my condition is that current date is more than 30 days from current date. I guess this logic does the task for me
@AlexeyMezenin That's what the original asker is looking for; using today as an example (December 13th), "more than 30 days from today" would be users created before November 13th.
I guess his more means later here. Also Carbon::now() ==> I want as ==> Carbon::now() - 30days pretty much explains what OP wants.
Aah yes... sorry I guess I was not clear. Yes "later" is what i meant
|
19

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

1 Comment

I like this one since it's using the now() helper.
10

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

1 Comment

could make it date('Y-m-d 00:00:00', strtotime("-30 days") to be more tidy
3

As with strtotime or DateTime, any (relative) date expressions can also be used with carbon::parse.

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::parse('Now -30 days'))
           ->get();

Alternatively for 'Now -30 Days', expressions '-30days' or '-720 hours' are also possible.

'Now -30 Days' takes into account the current time. If you need a time 00:00, use 'Today -30 Days'.

Comments

0

you can use carbon methods like subDays or subMonth methods

$object = User::whereActive()
           ->where( 'created_at', '<', now()->subDays($subDays))
           ->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.