After user registration in Laravel 11, a simple way to create an Event Listener

Follow these easy steps to create an Event Listener after user registration in Laravel 11.

Create an Event class file

php artisan make:event UserCreated

Create a Listener class file

php artisan make:listener SendWelcomeEmail --event=UserCreated

Add following codes in User model file

use App\Events\UserCreated;

Add the following codes in User class of User model file

protected $dispatchesEvents = [
     'created' => UserCreated::class,
];

Add the line in UserCreated event class file

use App\Models\User;

Replace with the following code in UserCreated class of UserCreated event class file

public function __construct(
     public User $user,
){}

Note: Keep the following class files and remove other from UserCreated event class file if not needed.

use App\Models\User;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

You can also keep the following traits and remove other from that file.

use Dispatchable, SerializesModels;

Now you can write the codes for sending email in the SendWelcomeEmail listener class file

public function handle(UserCreated $event): void
{
     // email address of the user just registered
     $email = $event->user->email;

     // Codes for sending email here
     ...
}

Similar Posts

Leave a Reply