Events are a way of letting other pieces of code extend your applications in a neat way. Some
other applications refer to this type of extension as a ‘Hook’. If you are a ‘PHP Guru’ you might
see some resemblances to the ‘Observer / Observable’ design pattern.
Events may have any number of listeners and firing them can return a varied number of
responses. I think the best way to learn will be to see this in action. Let’s take a closer look
at Events in Laravel.
12.1 Fire An Event
3 $responses = Event::fire('dinner.time');
In this example we ‘trigger’, or ‘fire’ the event dinner.time which alerts all of the listeners of
the event that it is time to get your grub on. The $responses variable will contain an array of
responses that the listeners of the event will provide, more on that later.
We can also retrieve the first response from an event, rather than all of them. We simply call the
first() method instead of fire() and now we receive a single result like this.
3 $response = Event::first('dinner.time');
It’s worth noting that although we are only receiving one response, all of the events listeners will
be informed. This means that the event will be fired just as if it was using the fire() method,
but all responses apart from the first will be ignored.
The third option for firing an event is the until() method. This method will fire the event,
notifying each listener until the first response that is a ‘NON-NULL’ value is returned. The first
‘NON-NULL’ value is then passed to the $response variable.
3 $response = Event::until('dinner.time');
Well now that we know how to fire an event, let’s have a look at the other end of the spectrum.
We need to know how to register ourselves as a listener. We don’t want to miss our dinner!