How to use Laravel events?

I want to be notified when a new user arrives. In my controller, I fire the event as follows.

Event::fire('myapp.new_user', array($this->data['user']->email)); 

Where can I define a listener ?

 Event::listen('myapp.new_user', function ($uid) { Message::to("myemail@example.com") ->from("myemail@example.com", "My App") ->subject('New User') ->body("new user") ->html(true) ->send(); }); 

How does the listener know the event that was fired?

+8
php laravel
source share
3 answers

You need to make sure that your listeners are defined before executing your application logic, when events are thrown out, they can be caught by already registered listeners, they are not looking for new ones.

In small projects, I just place listeners in application/start.php at the bottom of the file. This file happens before your routes run and serves as a kind of application configuration file with some logic. You need to place these events at the bottom of the file, at least after the autoload mappings have been registered.

In larger projects, I will create application/listeners.php and require this file inside application/start.php for better readability.

Hope this helps!

+25
source share

try:

 Event::listen('myapp.new_user', function ($uid) { Message::to("myemail@example.com") ->from("myemail@example.com", "My App") ->subject('New User') ->body("new user") ->html(true) ->send(); return 'test my event'; }); 

http://laravel.com/docs/events

+2
source share

You can also define classes to handle specific events, and then use the service provider to register them.

The following is a basic example:

application /NewUserListener.php

The listener that is called when the event fires:

 class NewUserListener { public function handle($uid) { // Send an email here } } 

application /ListenerServiceProvider.php

ServiceProvider - remember and add this to the list of service providers in the L4 configuration.

 use Illuminate\Support\ServiceProvider; class ListenerServiceProvider extends ServiceProvider { public function register() { Event::listen('myapp.new_user', 'NewUserListener'); // Register more events here... } } 

If you organize listeners, etc. in folders with the appropriate name, it becomes much easier to maintain if you have a bunch of listeners later. You can also create and test listeners if you write them this way.

+2
source share

All Articles