smchae
smchae

Reputation: 1095

When to use events in Laravel

I am new to laravel, and I have a question about the usage of events.

As far as I understand, events are used when some actions such as registering users occur and handle logic following those actions such as sending a confirmation email.

But what I do not understand is that why can't I just create a helper function which would handle those actions instead of creating event and listener files.

In other words, what is the advantages of using events?

Thank you.

Upvotes: 10

Views: 4517

Answers (2)

Gaurav
Gaurav

Reputation: 1972

Using events and listeners instead of helpers can have 2 additional benefits:

  1. Stopping The Propagation Of An Event (without extra conditionals)
  2. Queuing the implementation login

    -> Mails, external calls, etc. take time. We can let the server do it later by using queues leading to the better User experience.

Upvotes: 3

Vũ Nhật Anh
Vũ Nhật Anh

Reputation: 512

Using events and listeners just another approach to implement that use observer pattern. Of course it has its own advantages. As the laravel document said:

Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can simply raise an OrderShipped event, which a listener can receive and transform into a Slack notification.

Upvotes: 5

Related Questions