Search code examples
laraveleloquentcronschedulelaravel-mail

How to notify the admin if the items(Multiple items) are going to expire in days later-Laravel


There are many items in the Items table and there is an expired date column in the items table. I just want to get a push notification every day before each items going expire one date before (Expire dates are different to each other and can have one expire date to multuple items). im new to laravel. Please help me.


Solution

  • This can be simply done with Laravel task scheduling

    1. You need to create a custom artisan command like

      php artisan make:command SendItemExpiryEmailsToAdmin
      

    1. Under App\Console\Commands You will find a class SendItemExpiryEmailsToAdmin should be created.

      i) First you need to define the signature of the command which will be used to call from the command line.

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

      ii) Inside the handle() of the same class, write your logic. A sample logic is given below. You will need to create a Mailable class to send the mail.

      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
      }
      

    1. Mailable to send the mail.

      i) Run the following command to create a mailable

      php artisan make:mail ItemsExpiryEmail
      

      ii) In the mailable, write your code. A sample code is given below, you can use $this->itemIds in the mail view as it is a public variable.

      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('test@example.com', 'Admin')
                  ->subject('Subject of the mail')
                  ->view('emails.adminNotification'); // adminNotification will be the view to be sent out as email body
          }
      }
      

    1. This command needs to be executed daily using the Cornjob.

    Try this, I'm sure this will help. Let me know if you have any questions.