So the way I see it is that a good Laravel application should be very model- and event-driven.
I have a Model called Article
. I wish to send email alert
In your case, you may also use following approach:
// Put this code in your Article Model
public static function boot() {
parent::boot();
static::created(function($article) {
Event::fire('article.created', $article);
});
static::updated(function($article) {
Event::fire('article.updated', $article);
});
static::deleted(function($article) {
Event::fire('article.deleted', $article);
});
}
Also, you need to register listeners in App\Providers\EventServiceProvider
:
protected $listen = [
'article.created' => [
'App\Handlers\Events\ArticleEvents@articleCreated',
],
'article.updated' => [
'App\Handlers\Events\ArticleEvents@articleUpdated',
],
'article.deleted' => [
'App\Handlers\Events\ArticleEvents@articleDeleted',
],
];
Also make sure you have created the handlers in App\Handlers\Events
folder/directory to handle that event. For example, article.created
handler could be like this:
mailer = $mailer;
}
public function articleCreated(Article $article)
{
// Implement mailer or use laravel mailer directly
$this->mailer->notifyArticleCreated($article);
}
// Other Handlers/Methods...
}