Skip to content

Instantly share code, notes, and snippets.

@nasrulhazim
Last active June 2, 2021 19:42
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save nasrulhazim/10ffa2cfafcaaf54784db6e566b5a7d3 to your computer and use it in GitHub Desktop.
Save nasrulhazim/10ffa2cfafcaaf54784db6e566b5a7d3 to your computer and use it in GitHub Desktop.
Send Welcome Email Notification with Event and Listener

Send Welcome Email Notification with Event and Listener

Step 1

Create SendWelcomeEmailNotification notification

php artisan make:notification SendWelcomeEmailNotification

Step 2

Create SendWelcomeEmail listener on user registration by register App\Listeners\SendWelcomeEmail to Illuminate\Auth\Events\Registered in app\Providers\EventServiceProvider.php.

protected $listen = [
    'Illuminate\Auth\Events\Registered' => [
        'App\Listeners\SendWelcomeEmail',
    ],
];

Then run this command in terminal:

php artisan event:generate

Step 3

Open up App\Listeners\SendWelcomeEmail.php, add the following lines:

<?php

namespace App\Listeners;

use App\Notifications\SendWelcomeEmailNotification;
use Illuminate\Auth\Events\Registered;

class SendWelcomeEmail
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Registered  $event
     * @return void
     */
    public function handle(Registered $event)
    {
        $event->user->notify(
            new SendWelcomeEmailNotification()
        );
    }
}

Step 4

Please ensured to setup your database and emails connection, and migrate the existing migration scripts. Then create auth scaffold if not done yet.

php artisan migrate && php artisan make:auth

Step 6

Then you're ready to register. You should receive email once registered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment