Laravel - Events


How can we create events and handlers?

php artisan make:event ProductWasCreatedEvent
Class ProductWasCreatedEvent extends Event {
  use SerializesModels;
  public $product;

   * Create a new event instance
   * @return void
  public function __construct(Product $product) {
    $this->product = $product;

Then in the Product model:

use Event;
use Acme\Events\ProductsWasCreatedEvent
$event = new ProductWasCreatedEvent($product);
php artisan handler:event NotifyUsersOfNewProduct --event="ProductWasCreatedEvent"

Look inside the app->Handlers for the new NotifyUsersOfNewProduct.php file and provide the concrete implementation for the handle method.

Register the provider. Look inside app->Providers for the EventServiceProvider.php file and modify it like:

use Acme\Events\ProductWasCreatedEvent;
use Acme\Handlers\Events\NotifyUsersOfNewProduct;

protected $listen = [
  ProductWasCreatedEvent:class => [
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License