【问题标题】:Laravel Date Difference with Carbon [duplicate]Laravel与碳的日期差异[重复]
【发布时间】:2019-05-04 23:07:04
【问题描述】:

我正在尝试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

【问题讨论】:

  • $user = User::where('email', $subscribe->email) 应该是 $user = User::where('email', $subscribe->email)->first( );
  • Package也是如此。
  • 如果我有多个不同用户的订阅怎么办?它只得到第一个对吗?
  • 在这种情况下使用“->get()”而不是“->first()”并使用foreach循环遍历这些用户并向这些用户中的每一个发送电子邮件。
  • 我刚刚添加它作为答案。将代码 sn-p 放在那里更容易。看看这是否适合你。

标签: laravel php-carbon laravel-mail


【解决方案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));
    }

【讨论】:

  • 不幸的是它不起作用,我最好的猜测是它无法找到用户,因为它总是返回[]
  • 我已经更新了答案。我的猜测是它会返回您分配给用户的空数组。问题可能出在第一行。
  • 救生员:D。非常感谢,它终于发送电子邮件了
  • 不客气! :)
【解决方案2】:

使用subDays()方法如下图:

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

【讨论】:

  • Q1 我是否需要循环播放才能让用户收到他们的电子邮件? Q2 如果我循环它,它会向它找到的第一个用户发送电子邮件吗?我应该如何在Mail::... 中定义结果数组?
  • 更新了我的问题。
  • 如果 expires_at 是一个时间戳,这不会很好,因为您正在查看一个精确的比较。
  • 是的时间戳,你现在建议什么?
  • @mafortis,一旦你有答案,你真的不应该添加额外的问题。阅读帮助下的“如何提问”部分。不要在一个问题上提出多个问题,SO 是一个问答网站,而不是一个可以广泛讨论答案的论坛。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 2018-08-05
  • 2015-11-27
  • 1970-01-01
  • 2015-03-23
  • 1970-01-01
  • 2015-04-27
相关资源
最近更新 更多