November 20, 2016 —John Koster
event($event, $payload = [], $halt = false)
The event
helper is a convenient way to dispatch a particular $event
to its listeners. An optional $payload
of data can also be supplied when dispatching the event. When the event is dispatched, all its listeners will be called and any responses from the listener will be added to an array. The array of responses is generally the return value of the event
function.
If the $halt
parameter is set to true
, the dispatcher will stop calling listeners after any of the listeners return a value that is not null
. If no listeners have returned a response and all listeners were called, the event
function will return null
.
The following examples will highlight the various ways to use the event
function:
1<?php 2 3/** 4 * The following code is simply creating a new event class 5 * to signal that a video was watched. 6 */ 7 8namespace App\Events; 9 10use App\Video;11use App\Events\Event;12use Illuminate\Queue\SerializesModels;13 14class VideoWasWatched extends Event15{16 use SerializesModels;17 18 public $video;19 20 /**21 * Create a new event instance.22 *23 * @param Video $video24 * @return void25 */26 public function __construct(Video $video)27 {28 $this->video = $video;29 }30}
An event can be fired by the name of a class like so:
1<?php2 3event('\App\Events\VideoWasWatched', $video);
Alternatively, an event can be fired by instantiating a new instance of the event class itself:
1<?php2 3event(new VideoWasWatched($video));
In the above example, a $payload
was not supplied. This is because the event instance itself will become the payload. It is equivalent to the following:
1<?php2 3$event = new VideoWasWatched($video);4event('App\Events\VideoWasWatched', $event);
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.