Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

laravel

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.

like image 886
Daniel Logvin Avatar asked Jul 12 '20 10:07

Daniel Logvin


People also ask

What is notify () in Laravel?

Laravel Notify is a package that lets you add custom notifications to your project. A diverse range of notification design is available.


1 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');
}
like image 160
Dirk Hoekstra Avatar answered Oct 31 '22 04:10

Dirk Hoekstra