Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gust's avatar
Level 1

Code inside event listener not working

Quiz app, laravel 5.2, mac I am trying to test an event listener when a user registers after having done php artisan make:auth that sends a welcome email

quizwhiz/app/Http/Controllers/Auth

public function postRegister(Request $request)
    {
        ...
        
        event(new UserRegistered(Auth::user()));

        return response()->json();
    }

quizwhiz/app/Events/Registration/UserRegistered.php

namespace App\Events\Registration;

use App\Events\Event;
use App\User;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

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

quizwhiz/app/Listeners/Registration/UserRegistered/SendWelcomeEmail.php

namespace App\Listeners\Registration\UserRegistered;
use App\Events\Registration\UserRegistered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

... 
public function handle(UserRegistered $event)
    {
        var_dump("Notify".$event->user->name.'that they are getting an email due to registration from the site');
    dd("stop");
    }

Adding the event seems to have halted the registration When I hit the registration button nothing happens now.

0 likes
3 replies
al0mie's avatar

check that you correctly bind event and listener in EventServiceProvider and override postRegister method

silverxjohn's avatar

I think the culprit is in this method:

public function postRegister(Request $request)
{
    ...
        
    event(new UserRegistered(Auth::user()));

    return response()->json();
}

The user is suppose to be register and not login. So Auth::user()(I'll assume) will be null.

EDIT: I just saw Laravel's postRegister() and see that the created user is authenticated. My answer is irrelevant.

However, as @al0mie said, check your app/providers/EventServiceProvider and make sure the listener 'listens' to the event.

Jaytee's avatar

Check the EventServiceProvider.

You should have an array similar to this:

protected $listen = [
        'App\Events\MyAwesomeEvent' => [
            'App\Listeners\MyAwesomeListener',
        ],
];

Also, make sure you're using the Event in your Authentication Controller.

Please or to participate in this conversation.