How to send a notification based on a date in laravel?

Viewed 7407

I'm trying to make for my backend to send a notification each day that that comes closer to an indicated date.

For example, if my user adds the date "13-07-2020", he should be getting a notification "your deadline is in 1 day!" (as today is 12).

I've read in the documentation of Laravel the section about "Task Scheduling", but I'm not sure how to implement it this way, each user will be getting its own notifications.

How is it possible to accomplish this? The documentation states: "Laravel's command scheduler allows you to fluently and expressively define your command schedule within Laravel itself." So, it makes me believe that it is just for commands.

3 Answers

I would approach this with Laravel commands.

Creating a command

To create a command you can run:

php artisan make:command NotifyUsers

This creates the NotifyUsers command. In the handle() function of the command, you can send a message to each user that has a deadline date set.

public function handle() {
  $users = User::whereNotNull('deadline_date')->get();
  foreach($users as $user) {
    $diffInDays = $user->deadline_date->diff(Carbon::now())->days;

    $user->notify("Your deadline is in $diffInDays day!");
  }
}

I set the signature of the command to the following:

protected $signature = 'users:notify';

This means you can call the command by runnning

php artisan users:notify

Scheduling the command

In the Console/Kernel.php class you can schedule the command. First you should add it to the $commands array:

protected $commands = [
  NotifyUsers::class,
];

And in the schedule() function you can schedule the command to run once every day.

protected function schedule(Schedule $schedule) {
  // Here you can execute the command once every day
  $schedule->command('users:notify')->dailyAt('14:00');
}

"Task Scheduling" - it means that some action is done by cron.

I don't know what you mean by "notification". You mean in app or by email?

  1. notification in App - you create a scheduled action, where you insert data into notification table. Table can looks like this: id, user_id, task_id, day
  2. email - you send emails to users in that scheduled action.

Because the question is non-technical, my answer will also contain no code.

Create a scheduler command that runs "quite frequently" (like every 5 minutes or so). The purpose of this command is to constantly iterate through all of the resources with the date specified by your users and pick those that match a rule similar to:

Date of the record in the future minus deadline = now()

In other words you constantly loop through all records that are prior to deadline, and pick those that match a deadline date. Once picked, remember to mark them as "done" after you perform your business logic, so that scheduled command won't pick them again. This can be achieved by an extra boolean flag.

Related