Rony Banik Arko
Rony Banik Arko

Reputation: 131

Listening and Firing an Event on a Particaular Date in Laravel

I am trying to Make a Notification Script for my own use. Here is What I am trying to achieve. When user is Registering I am grabbing their email address and the notification date which is given by them and saving these in the profile table. Now on that specified notification date the Application will automatically send them an email. So far my idea for doing this easily is to use an "Event"; But please feel free to correct me if I am wrong. Based on my idea here is what I am planning to do; for the email I might register a class as the data for the Event.

But my first question is how can I listen for an event for that notification date?

And I want to send them a notification every month so after sending an email I am gonna add one month to the old notification date given by the user. Adding one month would be easy as I am using "Carbon" on the input while saving the notification date.

So, my second question is after the notification date is updated how can I listen for that event again?

And lastly if I have 100 users and I want to send the same notification to everyone on the notification date given by them and a specific date such as at the beginning of each month. How can I do that recurrently?

Please feel free to give any kind of suggestion that might be easy to implement instead of what I am thinking.

Upvotes: 4

Views: 3283

Answers (1)

Victor
Victor

Reputation: 556

I feel like what you are trying to accomplish is better done through a scheduled command. Some people do this by creating cron jobs that will call a certain function when scheduled.

In Laravel 4 (I'm assuming that this is what you are using), there is a great package by indatus called dispatcher. I'll not go into how to set it up, as they have great documentation, but you can crate scheduled jobs where you will check every x days / minutes, etc. It's also more readable.

Dispatcher makes it very readable in comparison to cron jobs, for example:

```use Indatus\Dispatcher\Scheduling\ScheduledCommand; use Indatus\Dispatcher\Scheduling\Schedulable; use Indatus\Dispatcher\Drivers\DateTime\Scheduler;

class MyCommand extends ScheduledCommand {

//your command name, description etc.

public function schedule(Schedulable $scheduler)
{
    //every day at 4:17am
    return $scheduler
        ->daily()
        ->hours(4)
        ->minutes(17);
}

}

```

This functionality has been incorporated into laravel 5 so you don't have to install any extra packages if you are using that version.

Hope it helps.

[EDIT :] A great video by Jeffrey Way on how to set up and use dispatcher can be found here.

Upvotes: 1

Related Questions