Send Email Using Laravel 5.7 Events & Listeners

Rafa Rafael
Feb 22 · 2 min read

Laravel’s events provide a simple observer implementation, allowing you to subscribe and listen for various events that occur in your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/ListenersRead more

This tutorial assumes that you already created a new project using composer or via laravel new and setup your mail driver either using log or smtp.

On this Example I wanted to email a registered user when he/she was added as a teacher by a student. So once the teacher (registered user) click accept on the email request by the student sent from my app it will change the accepted column to true in my teachers table.

Alright, without further ado let’s begin creating our files.

  1. Create a Mailable

php artisan make:mail PurposeOfThisMail

Then the actual code looks like this:

App\Mail\TeacherConfirmationEmail

TeacherConfirmationEmail is our mailable class. And if you have observed I set the modifier to public on each property so that we can use it directly in our view below (The email that will be receive by the teacher to accept the request).

resources/views/emails/teacher-confirmation.blade.php

We are done with the Mailable, next is to create now our event and listener to send the email to the teacher.

2. Create an Event and Listener

We create our event first,

php artisan make:event WhatIsHappening

Then the code will be,

app\Events\TeacherAdded.php

As you can see, our event has the same property with the mailable class as it is the wrapper that will accept the values that will be pass by the controller.

Next we will make our Listener,

php artisan make:listener SendTeacherConfirmationEmail --event=TeacherAdded

Since we used the --event= option it will automatically wired our TeacherAdded event class, then we send email using Mail::to and since the properties set to public in our event, we can easily access them using the $event->.

Once you are done we will register our listeners to our EventServiceProvider class which can be found in app\Providers\EventServiceProvider.php.

The actual code will look like this,

3. Fire the Event

Add the code below in the store method of your controller to fire the event and send the email request to the teacher after saving the teacher data or whatever you wanted that will need to send email.

event(new TeacherAdded($manager, $user));

4. The teacher accepted the request

Add the endpoint in routes/web.php to confirm that the teacher accepted the request.

Route::get(‘confirm/{teacher}/{student}’, ‘App\Http\Controllers\TeacherConfirmationController@index’ );

Then in controller that will process the update of the status will look like this,

app\Http\Controllers\TeacherConfirmationController.php

That’s it! You may now test sending email. Enjoy!

Rafa Rafael

Written by

Full Stack Developer (Laravel/Vue.js)