在我的应用程序中,我必须检查某个日期是否已过期,何时必须发送电子邮件。日期保存在Clients
表格中。如何在检索日期中添加5天,以便我可以检查它是否会在5天内过期?到目前为止我的功能。
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
}
}
}
答案 0 :(得分:3)
您应该使用whereDate()
将查询作为查询的一部分。您在PHP方面过滤这些数据没有任何好处:
$now = Carbon::now()->addDays(5);
$users =\App\Client::select('subscription_ends_at')
->groupBy('subscription_ends_at')
->whereDate('date_expired', '>', $now->toDateString()),
->get();
关于Eloquent的文档where here。
修改强>
您的查询对我来说是破碎的。使用groupBy()
将使它只返回一小部分客户端,将那些在同一天到期的客户端分组到一个条目中。这样做会导致发送通知的目的失败,因为不是每个人都会得到通知,所以我宁愿完全删除groupBy()
。
答案 1 :(得分:1)
使用addDays()
添加天数:
Carbon::now()->addDays(5);
此外,将此添加到查询中总是一个好主意,而不是加载所有数据和过滤器集合:
->where('subscription_ends_at', '>', Carbon::now()->addDays(5))
如果您将subscription_ends_at
添加到$dates
媒体资源,这将有效。