Reputation: 4125
In my application I have to check whether or not a certain date has expired, when so a e-mail has to be send out. The date's are saved in the Clients
table. How can I add 5 days to the retrieved date, so I can check whether or not it will be expired in 5 days? The function which I have until now.
public function handle() {
$users =\App\Client::select('subscription_ends_at')
->groupBy('subscription_ends_at')
->get();
$data_now = Carbon::now();
foreach($date_expired as $users ){
// $date_expired + 5 days
if($date_expired > $data_now){
//Send e-mail
}
}
}
Upvotes: 3
Views: 5860
Reputation: 75629
You should make your comparision part of your query by using whereDate()
. There's no benefit in your case for filtering this data on PHP side:
$now = Carbon::now()->addDays(5);
$users =\App\Client::select('subscription_ends_at')
->groupBy('subscription_ends_at')
->whereDate('date_expired', '>', $now->toDateString()),
->get();
Docs on Eloquent where clauses here.
EDIT
Your query is broken for me. Using groupBy()
will make it return only a fraction of clients grouping those expiring the same day into one entry. This in result defeats the purpose of sending notifications as not everyone will get it, so I'd rather remove groupBy()
completely.
Upvotes: 4
Reputation: 163808
Use addDays()
to add days:
Carbon::now()->addDays(5);
Also, it's always a good idea to add this to the query instead of loading all the data and filter collection:
->where('subscription_ends_at', '>', Carbon::now()->addDays(5))
This will work if you'll add subscription_ends_at
to the $dates
property.
Upvotes: 2