Events

Introduction

Laravel's events provides a simple observer implementation, allowing you to subscribe and listen for events in your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners.

Registering Events / Listeners

The EventServiceProvider included with your Laravel application provides a convenient place to register all event listeners. The listen property contains an array of all events (keys) and their listeners (values). Of course, you may add as many events to this array as your application requires. For example, let's add our PodcastWasPurchased event:

  1. /**
  2. * The event listener mappings for the application.
  3. *
  4. * @var array
  5. */
  6. protected $listen = [
  7. 'App\Events\PodcastWasPurchased' => [
  8. 'App\Listeners\EmailPurchaseConfirmation',
  9. ],
  10. ];

Generating Event / Listener Classes

Of course, manually creating the files for each event and listener is cumbersome. Instead, simply add listeners and events to your EventServiceProvider and use the event:generate command. This command will generate any events or listeners that are listed in your EventServiceProvider. Of course, events and listeners that already exist will be left untouched:

  1. php artisan event:generate

Registering Events Manually

Typically, events should be registered via the EventServiceProvider $listen array; however, you may also register events manually with the event dispatcher using either the Event facade or the Illuminate\Contracts\Events\Dispatcher contract implementation:

  1. /**
  2. * Register any other events for your application.
  3. *
  4. * @param \Illuminate\Contracts\Events\Dispatcher $events
  5. * @return void
  6. */
  7. public function boot(DispatcherContract $events)
  8. {
  9. parent::boot($events);
  10. $events->listen('event.name', function ($foo, $bar) {
  11. //
  12. });
  13. }

Wildcard Event Listeners

You may even register listeners using the * as a wildcard, allowing you to catch multiple events on the same listener. Wildcard listeners receive the entire event data array as a single argument:

  1. $events->listen('event.*', function (array $data) {
  2. //
  3. });

Defining Events

An event class is simply a data container which holds the information related to the event. For example, let's assume our generated PodcastWasPurchased event receives an Eloquent ORM object:

  1. <?php
  2. namespace App\Events;
  3. use App\Podcast;
  4. use App\Events\Event;
  5. use Illuminate\Queue\SerializesModels;
  6. class PodcastWasPurchased extends Event
  7. {
  8. use SerializesModels;
  9. public $podcast;
  10. /**
  11. * Create a new event instance.
  12. *
  13. * @param Podcast $podcast
  14. * @return void
  15. */
  16. public function __construct(Podcast $podcast)
  17. {
  18. $this->podcast = $podcast;
  19. }
  20. }

As you can see, this event class contains no special logic. It is simply a container for the Podcast object that was purchased. The SerializesModels trait used by the event will gracefully serialize any Eloquent models if the event object is serialized using PHP's serialize function.

Defining Listeners

Next, let's take a look at the listener for our example event. Event listeners receive the event instance in their handle method. The event:generate command will automatically import the proper event class and type-hint the event on the handle method. Within the handle method, you may perform any logic necessary to respond to the event.

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PodcastWasPurchased;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class EmailPurchaseConfirmation
  7. {
  8. /**
  9. * Create the event listener.
  10. *
  11. * @return void
  12. */
  13. public function __construct()
  14. {
  15. //
  16. }
  17. /**
  18. * Handle the event.
  19. *
  20. * @param PodcastWasPurchased $event
  21. * @return void
  22. */
  23. public function handle(PodcastWasPurchased $event)
  24. {
  25. // Access the podcast using $event->podcast...
  26. }
  27. }

Your event listeners may also type-hint any dependencies they need on their constructors. All event listeners are resolved via the Laravel service container, so dependencies will be injected automatically:

  1. use Illuminate\Contracts\Mail\Mailer;
  2. public function __construct(Mailer $mailer)
  3. {
  4. $this->mailer = $mailer;
  5. }

Stopping The Propagation Of An Event

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener's handle method.

Queued Event Listeners

Need to queue an event listener? It couldn't be any easier. Simply add the ShouldQueue interface to the listener class. Listeners generated by the event:generate Artisan command already have this interface imported into the current namespace, so you can use it immediately:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PodcastWasPurchased;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class EmailPurchaseConfirmation implements ShouldQueue
  7. {
  8. //
  9. }

That's it! Now, when this listener is called for an event, it will be queued automatically by the event dispatcher using Laravel's queue system. If no exceptions are thrown when the listener is executed by the queue, the queued job will automatically be deleted after it has processed.

Manually Accessing The Queue

If you need to access the underlying queue job's delete and release methods manually, you may do so. The Illuminate\Queue\InteractsWithQueue trait, which is imported by default on generated listeners, gives you access to these methods:

  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\PodcastWasPurchased;
  4. use Illuminate\Queue\InteractsWithQueue;
  5. use Illuminate\Contracts\Queue\ShouldQueue;
  6. class EmailPurchaseConfirmation implements ShouldQueue
  7. {
  8. use InteractsWithQueue;
  9. public function handle(PodcastWasPurchased $event)
  10. {
  11. if (true) {
  12. $this->release(30);
  13. }
  14. }
  15. }

Firing Events

To fire an event, you may use the Event facade, passing an instance of the event to the fire method. The fire method will dispatch the event to all of its registered listeners:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Event;
  4. use App\Podcast;
  5. use App\Events\PodcastWasPurchased;
  6. use App\Http\Controllers\Controller;
  7. class UserController extends Controller
  8. {
  9. /**
  10. * Show the profile for the given user.
  11. *
  12. * @param int $userId
  13. * @param int $podcastId
  14. * @return Response
  15. */
  16. public function purchasePodcast($userId, $podcastId)
  17. {
  18. $podcast = Podcast::findOrFail($podcastId);
  19. // Purchase podcast logic...
  20. Event::fire(new PodcastWasPurchased($podcast));
  21. }
  22. }

Alternatively, you may use the global event helper function to fire events:

  1. event(new PodcastWasPurchased($podcast));

Broadcasting Events

In many modern web applications, web sockets are used to implement real-time, live-updating user interfaces. When some data is updated on the server, a message is typically sent over a websocket connection to be handled by the client.

To assist you in building these types of applications, Laravel makes it easy to "broadcast" your events over a websocket connection. Broadcasting your Laravel events allows you to share the same event names between your server-side code and your client-side JavaScript framework.

Configuration

All of the event broadcasting configuration options are stored in the config/broadcasting.php configuration file. Laravel supports several broadcast drivers out of the box: Pusher, Redis, and a log driver for local development and debugging. A configuration example is included for each of these drivers.

Broadcast Prerequisites

The following dependencies are needed for event broadcasting:

  • Pusher: pusher/pusher-php-server ~2.0
  • Redis: predis/predis ~1.0

Queue Prerequisites

Before broadcasting events, you will also need to configure and run a queue listener. All event broadcasting is done via queued jobs so that the response time of your application is not seriously affected.

Marking Events For Broadcast

To inform Laravel that a given event should be broadcast, implement the Illuminate\Contracts\Broadcasting\ShouldBroadcast interface on the event class. The ShouldBroadcast interface requires you to implement a single method: broadcastOn. The broadcastOn method should return an array of "channel" names that the event should be broadcast on:

  1. <?php
  2. namespace App\Events;
  3. use App\User;
  4. use App\Events\Event;
  5. use Illuminate\Queue\SerializesModels;
  6. use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
  7. class ServerCreated extends Event implements ShouldBroadcast
  8. {
  9. use SerializesModels;
  10. public $user;
  11. /**
  12. * Create a new event instance.
  13. *
  14. * @return void
  15. */
  16. public function __construct(User $user)
  17. {
  18. $this->user = $user;
  19. }
  20. /**
  21. * Get the channels the event should be broadcast on.
  22. *
  23. * @return array
  24. */
  25. public function broadcastOn()
  26. {
  27. return ['user.'.$this->user->id];
  28. }
  29. }

Then, you only need to fire the event as you normally would. Once the event has been fired, a queued job will automatically broadcast the event over your specified broadcast driver.

Overriding Broadcast Event Name

By default, the broadcast event name will be the fully qualified class name of the event. Using the example class above, the broadcast event would be App\Events\ServerCreated. You can customize this broadcast event name to whatever you want using the broadcastAs method:

  1. /**
  2. * Get the broadcast event name.
  3. *
  4. * @return string
  5. */
  6. public function broadcastAs()
  7. {
  8. return 'app.server-created';
  9. }

Broadcast Data

When an event is broadcast, all of its public properties are automatically serialized and broadcast as the event's payload, allowing you to access any of its public data from your JavaScript application. So, for example, if your event has a single public $user property that contains an Eloquent model, the broadcast payload would be:

  1. {
  2. "user": {
  3. "id": 1,
  4. "name": "Jonathan Banks"
  5. ...
  6. }
  7. }

However, if you wish to have even more fine-grained control over your broadcast payload, you may add a broadcastWith method to your event. This method should return the array of data that you wish to broadcast with the event:

  1. /**
  2. * Get the data to broadcast.
  3. *
  4. * @return array
  5. */
  6. public function broadcastWith()
  7. {
  8. return ['user' => $this->user->id];
  9. }

Consuming Event Broadcasts

Pusher

You may conveniently consume events broadcast using the Pusher driver using Pusher's JavaScript SDK. For example, let's consume the App\Events\ServerCreated event from our previous examples:

  1. this.pusher = new Pusher('pusher-key');
  2. this.pusherChannel = this.pusher.subscribe('user.' + USER_ID);
  3. this.pusherChannel.bind('App\\Events\\ServerCreated', function(message) {
  4. console.log(message.user);
  5. });

Redis

If you are using the Redis broadcaster, you will need to write your own Redis pub/sub consumer to receive the messages and broadcast them using the websocket technology of your choice. For example, you may choose to use the popular Socket.io library which is written in Node.

Using the socket.io and ioredis Node libraries, you can quickly write an event broadcaster to publish all events that are broadcast by your Laravel application:

  1. var app = require('http').createServer(handler);
  2. var io = require('socket.io')(app);
  3. var Redis = require('ioredis');
  4. var redis = new Redis();
  5. app.listen(6001, function() {
  6. console.log('Server is running!');
  7. });
  8. function handler(req, res) {
  9. res.writeHead(200);
  10. res.end('');
  11. }
  12. io.on('connection', function(socket) {
  13. //
  14. });
  15. redis.psubscribe('*', function(err, count) {
  16. //
  17. });
  18. redis.on('pmessage', function(subscribed, channel, message) {
  19. message = JSON.parse(message);
  20. io.emit(channel + ':' + message.event, message.data);
  21. });

Event Subscribers

Event subscribers are classes that may subscribe to multiple events from within the class itself, allowing you to define several event handlers within a single class. Subscribers should define a subscribe method, which will be passed an event dispatcher instance:

  1. <?php
  2. namespace App\Listeners;
  3. class UserEventListener
  4. {
  5. /**
  6. * Handle user login events.
  7. */
  8. public function onUserLogin($event) {}
  9. /**
  10. * Handle user logout events.
  11. */
  12. public function onUserLogout($event) {}
  13. /**
  14. * Register the listeners for the subscriber.
  15. *
  16. * @param Illuminate\Events\Dispatcher $events
  17. */
  18. public function subscribe($events)
  19. {
  20. $events->listen(
  21. 'App\Events\UserLoggedIn',
  22. 'App\Listeners\[email protected]'
  23. );
  24. $events->listen(
  25. 'App\Events\UserLoggedOut',
  26. 'App\Listeners\[email protected]'
  27. );
  28. }
  29. }

Registering An Event Subscriber

Once the subscriber has been defined, it may be registered with the event dispatcher. You may register subscribers using the $subscribe property on the EventServiceProvider. For example, let's add the UserEventListener.

  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
  4. use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
  5. class EventServiceProvider extends ServiceProvider
  6. {
  7. /**
  8. * The event listener mappings for the application.
  9. *
  10. * @var array
  11. */
  12. protected $listen = [
  13. //
  14. ];
  15. /**
  16. * The subscriber classes to register.
  17. *
  18. * @var array
  19. */
  20. protected $subscribe = [
  21. 'App\Listeners\UserEventListener',
  22. ];
  23. }

Framework Events

Laravel provides a variety of "core" events for actions performed by the framework. You can subscribe to them in the same way that you subscribe to your own custom events:

EventParameter(s)
artisan.start$application
auth.attempt$credentials, $remember, $login
auth.login$user, $remember
auth.logout$user
cache.missed$key
cache.hit$key, $value
cache.write$key, $value, $minutes
cache.delete$key
connection.{name}.beganTransaction$connection
connection.{name}.committed$connection
connection.{name}.rollingBack$connection
illuminate.query$query, $bindings, $time, $connectionName
illuminate.queue.after$connection, $job, $data
illuminate.queue.failed$connection, $job, $data
illuminate.queue.stoppingnull
mailer.sending$message
router.matched$route, $request
composing:{view name}$view
creating:{view name}$view