laravel - 如果元素(多个元素)将在几天后过期,如何通知管理员-Laravel

标签 laravel eloquent cron schedule laravel-mail

项目表中有许多项目,并且项目表中有一个过期日期列。我只想每天在每件商品在前一天到期之前收到推送通知(到期日期彼此不同,并且多个商品可以有一个到期日期)。我是 Laravel 新手。请帮助我。

最佳答案

这可以简单地用 Laravel task scheduling 来完成

  1. 您需要创建一个 custom artisan command喜欢

    php artisan make:command SendItemExpiryEmailsToAdmin
    

  • App\Console\Commands下,您会发现应该创建一个SendItemExpiryEmailsToAdmin类。

    i) 首先,您需要定义将用于从命令行调用的命令的签名。

    protected $signature = 'email:send-item-expiry-email-to-admin';
    

    ii) 在同一个类的 handle() 中,编写您的逻辑。下面给出了示例逻辑。您需要创建一个 Mailable class发送邮件。

    public function handle() {
        // To fetch all the items ids which are going to expired today.
        $itemsIds = Items::whereBetween('expired',
                [Carbon::now()->setTime(0,0)->format('Y-m-d H:i:s'),
                Carbon::now()->setTime(23,59,59)->format('Y-m-d H:i:s')])
             ->pluck('id')
             ->toArray();
        $itemsIds = implode(" ", $itemsIds);
        Mail::queue(new ItemsExpiryEmail($itemsIds));
        // If you are not using queue, just replace `queue` with `send` in above line
    }
    

  • Mailable发送邮件。

    i) 运行以下命令来创建可邮寄的邮件

    php artisan make:mail ItemsExpiryEmail
    

    ii) 在可邮寄邮件中,编写您的代码。下面给出了示例代码,您可以在邮件 View 中使用 $this->itemIds,因为它是公共(public)变量。

    class ItemsExpiryEmail extends Mailable
    {
        use Queueable, SerializesModels; // don't forget to import these.
        public $itemIds;
    
        public function __construct($itemIds)
        {
            $this->itemIds = $itemIds;
        }
    
        public function build()
        {
            return $this->view('emails.orders.shipped');
            return $this->to('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="453120363105203d24283529206b262a28" rel="noreferrer noopener nofollow">[email protected]</a>', 'Admin')
                ->subject('Subject of the mail')
                ->view('emails.adminNotification'); // adminNotification will be the view to be sent out as email body
        }
    }
    

  • 该命令需要每天使用 Cornjob 执行.
  • 试试这个,我相信这会有帮助。如果您有任何疑问,请告诉我。

    关于laravel - 如果元素(多个元素)将在几天后过期,如何通知管理员-Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59550293/

    相关文章:

    php - 如何实现数据库表中多列的唯一约束?

    处理 "callbacks"计划执行的 Java 库类?

    ruby-on-rails - Rails 测试计划的邮件抽取任务

    cron - rsync 代码将运行,但不在 cron 中运行

    php - Mysql 连接除了 SELECT * INTO OUTFILE 语句外都有效

    laravel - 在我的项目中删除 node_modules 目录

    Laravel 4 模型验证与 Controller 验证

    php - Laravel > Eloquent 批量加载

    mysql - 无法约束 Laravel 和 MySql 上的关联表

    php - 如何从原始对象创建 Eloquent 模型实例?