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 alerts when the following events happen:
- When an Article is created
- When an Article is updated
- When an Article is deleted
The docs say I can use Model Events and register them within the boot()
function of App\Providers\EventServiceProvider
.
But this is confusing me because...
- What happens when I add further models like
Comment
orAuthor
that need full sets of all their own Model Events? Will the singleboot()
function ofEventServiceProvider
just be absolutely huge? - What is the purpose of Laravel's 'other' Events? Why would I ever need to use them if realistically my events will only respond to Model CRUD actions?
I am a beginner at Laravel, having come from CodeIgniter, so trying to wrap my head around the proper Laravel way of doing things. Thanks for your advice!
Recently I came to same problem in one of my Laravel 5 project, where I had to log all Model Events. I decided to use
Traits
. I createdModelEventLogger
Trait and simply used in all Model class which needed to be logged. I am going to change it as per your need Which is given below.Now you can use this trait in any Model you want to throw events for. In your case in
Article
Model.Now in your
app/Providers/EventServiceProvider.php
, inboot()
method register Event Handler forArticle
.Now create Class
ArticleEventHandler
underapp/Handlers/Events
directory as below,As you can see from different answers, from different Users, there are more than 1 way of handling Model Events. There are also Custom events That can be created in Events folder and can be handled in Handler folder and can be dispatched from different places. I hope it helps.
1) You may create an event listener for each new Model (ArticleEventSubscriber,CommentEventSubscriber) at boot method:
EventServiceProvider.php
or you may also use
$subscribe
propertyThere are many ways to listen and handle events. Take a look to current master documentation for discovering more ways(like usings closures) to do so : Laravel Docs (master) and this other answer
2) Model events are just events provided by default by Eloquent.
https://github.com/illuminate/database/blob/491d58b5cc4149fa73cf93d499efb292cd11c88d/Eloquent/Model.php#L1171
https://github.com/illuminate/database/blob/491d58b5cc4149fa73cf93d499efb292cd11c88d/Eloquent/Model.php#L1273