DEV Community

Ahmed sliman
Ahmed sliman

Posted on

Laravel Events 101

What is Event-Driven Programming?

Simply put, events are actions that occur within an application. Coming from the world of JavaScript, you probably understand events as user actions such as mouse click, mouseover, key press, etc. In Laravel, events can be various actions that occur within an application such as email notifications, logging, user sign-up, CRUD operations, etc. Laravel events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application.

Why should we use Events?!

  • Easier to maintain (SOLID).
  • Less risk of regression,
  • Make classes responsible for only one thing,
  • Make team’s work easier,
  • Expect the unexpected, If you ever need to add new functionality, all you need to do is create a new listener and register it with the event. Job is done!
  • Your logic is separated and now the Controller has much-reduced responsibility
  • Allow asynchronous tasks easily (queues in Laravel).
  • Be ready for broadcasting

Let's compare two pieces of code with/without events

With

Alt Text

Without

Alt Text

How do we create Events?

Defining Our Events

php artisan make:event UserRegistered

The event has been created successfully

php artisan make:listener SendWelcomeMail --event=UserRegistered

The listener has been created successfully

php artisan make:listener SignupForWeeklyNewsletter --event=UserRegistered

The listener has been created successfully

php artisan make:listener SendSMS --event=UserRegistered

The listener has been created successfully

ESP - EventServiceProvider

Alt Text

php artisan event:generate

Events and Listeners generated successfully

Stopping The Propagation Of An Event

Alt Text

Eloquent Native Events

With his Eloquent model, Laravel will automatically fire created, saved, updated and deleted events respectively.

To start listening to model events, define a $dispatchesEvents property on your Eloquent model. This property maps various points of the Eloquent model's lifecycle to your event classes. Each model event class should expect to receive an instance of the affected model via its constructor.

Eloquent Native Events

Alt Text

Alt Text

Top comments (0)