Laravel与碳的日期差异

时间:2018-12-03 16:01:59

标签: laravel php-carbon laravel-mail

我正在尝试send email three days before the expired date,,但不确定如何?

逻辑

  1. 检索剩余三天到期的所有订户
  2. 发送电子邮件给他们的用户

代码

我需要检查名为subscribes.的时间戳的表

$subscribes = Subscribe::all();

此表有一个名为expires_at的列,我需要检查一下以找到3 days left.

还有我的邮件

Mail::to($user->email)->send(new SubscribeExpire($user, $subscribe));

我对这种碳计算感到困惑,有人可以帮助吗?

更新

基于下面的答案,我现在有这个:

$subscribes = Subscribe::where('expires_at', Carbon::now()->subDays(3))->get();
        $user = [];
        $package = [];
        foreach($subscribes as $subscribe){
            $user = User::where('email', $subscribe->email);
            $package = Package::where('id', $subscribe->package_id);
        }

        Mail::to($user->email)->send(new SubscribeExpire($user, $package));

但是当我运行命令时会出现此错误

ErrorException  : Trying to get property 'email' of non-object

2 个答案:

答案 0 :(得分:1)

使用subDays()方法,如下所示:

$subscribes = Subscribe::where('expires_at', Carbon::now()->subDays(3))->get();

答案 1 :(得分:1)

  // here you get subscribes  
  // if you are going to send three days before the expiry date, this means we need to check if expires_at is in three days so probably need to add days. Or maybe even check if time left before expiration is more than three days and less than one day and run it once per day?
  $subscribes = Subscribe::whereDate('expires_at', Carbon::now()->addDays(3))->get();
    $user = [];
    $package = [];
    foreach($subscribes as $subscribe){
        // you probably have only one user with this email
        $user = User::where('email', $subscribe->email)->first();
        // you probably have one associated package
        $package = Package::where('id', $subscribe->package_id)->first();
    }
    // check if user and package are found
    if(is_object($user) && is_object($package)){
      Mail::to($user->email)->send(new SubscribeExpire($user, $package));
    }