in Laravel

Laravel Send Email When New User Registers

In this tutorial we're going to learn how we can send an email to the application admin user when a new user registers to your Laravel application.

In this example we're going to use events and listeners to know when a user has registered and the listener will then send an email to the admin of the application.

Register Controller

When using Laravel it has a built in way you can generate the boilerplate files for handling registration and logins for your application.

To create this boilerplate you simply use the following command.

php artisan make:auth

You will now have a new folder in your App/Http/Controllers folder called Auth. This will have controllers for logging in, register, forgotten password and resetting your password.

We will need to edit the RegisterController.php to dispatch a new event after the user has been created.

Event Service Provider

With the event dispatched we need to register the event and list out which listeners to use.

Add the following to your application event provider.

To generate new events you can add this to the $listen property. You list out an array using the event class as the key of the array and listeners are the node vales of the array. This means that a single event can perform multiple actions by adding more listeners to the event array.

New User Event

Next we need to create the class for the new user event. All we have to do in this class is accept the user model in the constructor and store this inside a public property.

New User Listener

With the event created we can now create the listener that will run when the event is dispatched.

The listener will need to take the user from the event class and send an email to the global mail.from.address. In the config folder you have a default mail.php file this has all the default settings for the email of your app. One of these settings is the global from and name email address for your application. As this is normally the admin user so we will be using this global email address in this example.

New User Mailable

The listener will send a mailable class for the email.

The mailable class uses the markdown component functionality of Laravel and pass in the new user into the blade component. We can then post this information to the admin user so they know who has just signed up to the application.

New User Email Markdown

The email markdown file is just a blade template for the HTML that is sent from your Mailable class. In this example it's going to be very sent forward we can just send through the email address of the user that registered to your application.

That's it, that's all the code you need to send the admin an alert when a new user registers to your application.

Login to access all content on Paulund

Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email