这是我的情况:
在我的数据库中,有一个表users
。表中的行还具有字段password_changed_at
。现在,我想选择password_changed_at
字段早于30天的所有用户并发送推送通知,但是我对如何使用Carbon做到这一点感到困惑。我的代码现在看起来像这样:
public function passwordExpired() {
$dateTime = new DateTime();
$currentDateTime = $dateTime->format('Y-m-d H:i');
$users = User::where('password_changed_at', $currentDateTime)->get();
// $user = $request->user();
foreach ($users as $user) {
$password_changed_at = new Carbon(($user->password_changed_at) ? $user->password_changed_at : "");
if (Carbon::now()->diffInDays($password_changed_at) >= 30) {
foreach ($password_changed_at as $password)
{
// $user = $user->id;
$user->notify(new ReminderPassword($user));
$push = new PushNotification('apn');
$push->setMessage([
'aps' => [
'alert' => 'Reminder for your password "'.$user->email.'"',
'sound' => 'default',
'badge' => $user->unreadNotifications->count()
],
'extraPayLoad' => [
'custom' => 'My custom data',
]
]);
$push->setDevicesToken($user->deviceToken);
$push->send();
$feedback = $push->getFeedback();
}
答案 0 :(得分:0)
类似diffInDays
的工作方式却相反(例如,相差较远的一天将返回负值)。参见:https://carbon.nesbot.com/docs/#api-difference
因此您可以像这样更改代码:
public function passwordExpired() {
$dateTime = new DateTime();
$currentDateTime = $dateTime->format('Y-m-d H:i');
$users = User::where('password_changed_at', $currentDateTime)->get();
foreach ($users as $user) {
$password_changed_at = new Carbon(
($user->password_changed_at) ? $user->password_changed_at : ""
);
// DiffIndays works the other way round:
if ($password_changed_at->diffInDays(Carbon::now()) >= 30) {
$user->notify(new ReminderPassword($user));
$push = new PushNotification('apn');
$push->setMessage([
'aps' => [
'alert' => 'Reminder for your password "' . $user->email . '"',
'sound' => 'default', 'badge' => $user->unreadNotifications->count()
],
'extraPayLoad' => ['custom' => 'My custom data', ]
]);
$push->setDevicesToken($user->deviceToken);
$push->send();
$feedback = $push->getFeedback();
}
}
}
答案 1 :(得分:0)
使用$users = User::where('password_changed_at', $currentDateTime)->get();
,您选择所有已更改其日期今天的用户,但您希望选择所有已更改密码+30天之前的用户。
因此,您可以使用查询范围来选择它们。在您的Users类中添加以下内容:
class Users extends Authenticatable
{
// ...
public function scopePasswordOlderThan30Days(Builder $builder)
{
$expirationDate = Carbon::now()->subDays(30);
return $builder->where('password_changed_at', '<=', $expirationDate);
}
}
在您的函数中按以下方式使用它:
public function passwordExpired()
{
$users = User::passwordOlderThan30Days()->get();
$users->each(function(User $user) {
// notify the user
})
}