user3574492
user3574492

Reputation: 6435

Laravel 5.5 user event listener not working

I have set up an event that should run whenever a user registers successfully. The event runs but the listener handler is never triggered.

Any one know what I've done wrong here? I'm using Laravel 5.5 on a local development server (wamp).

It's not even getting to the listener's handle() function, I put a dump in there to test.

Below is my code:

Event:

class UserRegisteredEmail extends Event {
    use InteractsWithSockets, SerializesModels;

    public $user;
    public $password;

    public function __construct($user, $password)
    {
        $this->user = $user;
        $this->password = $password;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

Event Listener:

 class UserRegisteredEmailListener {

    public function __construct()
    {
    }

    public function handle(UserRegisteredEmail $event)
    {
        Notification::send($event->user, new NewAccountEmail($event->password));
    }
}

EventServiceProvider:

class EventServiceProvider extends ServiceProvider
{

    protected $listen = [
        'App\Events\Event' => [
            'App\Listeners\EventListener',
            'App\Listeners\UserRegisteredEmailListener'
        ],
    ];


    public function boot()
    {
        parent::boot();
        //
    }
}

UserService where the event is dispatched:

    DB::transaction(function () use ($user, $password, $role, $sendEmail) {
                    $this->userMeta->firstOrCreate([
                        'user_id' => $user->id
                    ]);

                if ($sendEmail) {
                    event(new UserRegisteredEmail($user, $password));
                }
            });

Upvotes: 2

Views: 2299

Answers (2)

Chris G
Chris G

Reputation: 7050

If that is your real EventServiceProvider it isn't correct, it should be something more like:

protected $listen = [
    'App\Events\UserRegisteredEmail' => [
        'App\Listeners\UserRegisteredEmailListener'
    ],
];

A separate, but semi-related note, you might want to rename some of your classes to be more generic. This helps in the future if you want to add any additional events/listeners. Maybe App\Events\UserRegisteredEmail could change to App\Events\UserWasCreated and App\Listeners\UserRegisteredEmailListener could change to App\Listeners\SendUserWelcomeEmail

Upvotes: 1

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You need to register it:

protected $listen = [
    'App\Events\UserRegisteredEmail' => [
        'App\Listeners\EventListener',
        'App\Listeners\UserRegisteredEmailListener'
    ],
];

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.

https://laravel.com/docs/5.5/events#registering-events-and-listeners

Upvotes: 0

Related Questions