April 14, 2018 —John Koster
The event
helper function 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.
The event
helper function can also be used to dispatch object based events without having to resolve the event dispatcher dependency.
The signature of the event
function is:
1function event(2 $eventObject3);4 5function event(6 $event,7 $payload = [],8 $halt = false9);
The following examples will highlight the various ways to use the event
function:
1/** 2 * The following code is simply creating a new event class 3 * to signal that a video was watched. 4 */ 5 6namespace App\Events; 7 8use App\Video; 9use App\Events\Event;10use Illuminate\Queue\SerializesModels;11 12class VideoWasWatched extends Event13{14 use SerializesModels;15 16 public $video;17 18 /**19 * Create a new event instance.20 *21 * @param Video $video22 * @return void23 */24 public function __construct(Video $video)25 {26 $this->video = $video;27 }28}
An event can be fired by the name of a class like so:
1event(\App\Events\VideoWasWatched::class, $video);
Alternatively, an event can be fired by instantiating a new instance of the event class itself:
1event(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$event = new VideoWasWatched($video);2event('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.