Lesson 9 – Events and Listeners

You can use Laravel Events and Listeners to create web applications while implementing the Observe Pattern. For example, you can use these events to generate a welcome email for any user who registers on your website.

You will use Artisan utility to create new events and listeners. However, you have to register the event and its corresponding listeners in App\Providers\EventServiceProvider class before generating any event. This is how you can do it.

protected $listen = [
    'App\Events\NewUserRegistered' => [
    'App\Listeners\SendWelcomeEmail',
    ],
   ];

There is also an alternate notation you can use to register events.

protected $listen = [
    \App\Events\NewUserRegistered::class => [
    \App\Listeners\SendWelcomeEmail::class,
    ],
   ];
php artisan generate:event 

The above command will create all the events and their corresponding listeners in app/events and app/listeners folders respectively.

READ ALSO
Lesson 3 – Laravel Views

A single event can have multiple listeners as shown in the following example.

protected $listen = [
    'Event' => [
    'Listner1', 'Listener2'
    ],
   ];

There is also a wrapper classes called NewUserRegistered for the user model you have just registered.

class NewUserRegistered extends Event
{
 use SerializesModels;
 public $user;
 /**
 * Create a new event instance.
 *
 * @return void
 */
 public function __construct(User $user)
https://riptutorial.com/ 93
 {
 $this->user = $user;
 }
}

The SendWelcomeEmail listener will handle the above event.

class SendWelcomeEmail
{
 /**
 * Handle the event.
 *
 * @param NewUserRegistered $event
 */
 public function handle(NewUserRegistered $event)
 {
 //send the welcome email to the user
 $user = $event->user;
 Mail::send('emails.welcome', ['user' => $user], function ($message) use ($user) {
 $message->from('hi@yourdomain.com', 'John Doe');
 $message->subject('Welcome aboard '.$user->name.'!');
 $message->to($user->email);
 });
 }
}

You also have to fire or call the event every time a new user registers on your website. You can accomplish this task in service, command, or controller depending upon where you implement the logic for user registration.

event(new NewUserRegistered($user));

In the last lesson of this course, we will study the File System in Laravel.

READ ALSO
Lesson 1 – Laravel Installation.