Building Your Own Email Subscribe Widget with Laravel
In the world we live in today, emails play an important role in communication. Companies use it to interact with their users and send out campaigns to have a wider audience reach. At some point, you may want to make your own platform that allows you to send messages to your subscribers on demand. This article covers exactly that.
Setting Up the Backend for Mail Sending
Before you can start sending emails, you need an email provider and in this tutorial we are going to be using Mailtrap. Mailtrap is a fake SMTP server built to allow development teams to test, view and share emails sent from the development and staging environments without spamming real customers.
Follow this link to signup
Once you’re signed in, you can access your inbox and get your details there.
Configure .env
Now that we have all the details we needs, the next thing we need to do is to edit our environment variables to contain your MAIL_USERNAME
and MAIL_PASSWORD
.
We also need to set our database which we are going to be using which is sqlite
. In the .env , we set our DB_CONNECTION
, create a databasse.sqlite
file and then add a link to the database.sqlite
file as the DB_DATABASE
.
To create the database.sqlite
file, run in the root directory of your project :
touch database/database.sqlite
Then add the following to your .env
. The DB_USERNAME
and DB_PASSWORD
do not matter when using sqlite
Update Configuration to Assign Driver
You also need to set the MAIL_DRIVER
to smtp
to help make let Laravel know that you are going to be using an SMTP server to handle sending your emails
Database migrations for Subscribers
After setting up our application to use Mailtrap to send mails, the next thing we want to do is to create the database migrations for the Subscribers. Here we create the subscribers table and also specify what fields our table with contain. We create a new migration by running the command :
php artisan make:model -m Subscribers
What the above does it that we make a model
for our subscribers and pass the -m
flag to specify that a migration should be made for the new model. This is equivalent to running :
php artisan make:model Subscribersphp artisan make:migration create_subscribers_table
Subscribers Model
The subscribers model is simple. In here, we specify the mass assignable values and make use of SoftDeletes
. SoftDeletes
in simple terms is basically telling your database not to fully delete rows in the table but rather set their deleted_at
fields to the actual time the delete command was run. This in turn omits the row from being shown in further search results. Our Subscriber.php
model looks like this:
and the migration file looks as follows:
After the migration file has been set up, we run the migration by running the command:
php artisan migrate
Application Routes
In this application, we have 5 simple routes :
/
route is the landing page for the app and it shows the users a friendly welcome screen./signup
route takes the user to the page toSubscribe
to receive updates/savesubscribers
route acceptsPOST
data from the form on thesignup
page and then sends it to thesubscribe
action of theSignUpController
/compose
route is for the owner of the platform to create content for the email he/she is wants to share to subscribers/send
route acceptsPOST
data containing the message to be sent and passes it to thesend
action of theEmailController
Signing Up & Emailing New Subscribers
Now that you have all your routes set up, you’ll need to set up the logic behind the signup and emaling of our new subscribers. To properly implement this, create a controller for this.
php artisan make:controller SignUpController
The SignUpController
has two methods :
signup()
and subscribe()
. signup()
renders the a view for the user to enter their details to subscribe and subscribe()
contains the logic.
In the SignUpController.php
, we have:
Lets critically examine the signature of the subscribe
function:
We have as a parameter a SubscribeRequest
object. Now you may be wondering what the SubscribeRequest
is all about. To allow us validate the data being sent to the SignUpController
, we created a FormRequest
and this is done by running:
php artisan make:request SubscribeRequest
in the SubscribeRequest.php
, we have the following:
As we see above, we set some of the rules required for the request to be accepted in the rules()
. Once all the rules are met then we move back into the controller.
Now going back to the subscribe
function of our SignUpController
. At this point, you don’t need to worry about the content of the $request
so we first create a Subscriber
object which belongs to the Subscriber
model we discuss earlier, then you save it to the database with the →save()
method:
Now, the next step is to send a mail to the subscriber letting them know that they have successfully subscribed to your platform. To do this, you make use of the Mail
facade provided by Laravel. You pass the blade template
which in our case is the email.subscribed
and any variables
you want to send when compiling the template. You also need to specify who the message is from
and who you are sending to
which is seen below.
Afterwards, you redirect your use to the signup
page with a status
message letting the use know that he/she is successfully subscribed.
Sending Mails to Retrieved List of Subscribers
Here, we want to send emails to our list of subscribers. To do this, we create a controller to handle the sending of mails to the subscribers list. We call our controller the EmailController
and we create it by running the command :
php artisan make:controller EmailController
Our controller has two main functions : compose()
which renders the view for the admin to create the message to sent in the email and send()
which handles the logic of sending the mails to the subscribers.
The EmailController
looks as follows:
Now lets examine the signature of the send()
function
It accepts the an object of the SendRequest
class as a parameter. The SendRequest
class is responsible for validating the form data that is send from the admin dashboard and it looks like this:
We specify the validation rules in the rules()
function of the SendRequest
class.
Now going back to the send
function of the EmailController
. First, we fetch all the subscribers we have and then send the mail to all of the subscribers using the Mail
Facade. We pass the blade template
and the name
, title
and content
as the parameters for generation of the view.
Implementing Queues to Defer Email Batches
Ideally, the method above works; but when we take into consideration the efficiency and the run time of the application, the normal Mail::send()
may not work all the time. There is a need to implement queues in your application to make your sending of emails more efficient.
So now, we are going to use Mailables with queues. To create a Mailable, we run the command,
php artisan make:mail CampaignReady
now in the CampaignReady.php
, there’s a couple of things that need to be done :
When have 3 public variables declared in the class :
Subscriber
- The subscribertitle
- The title of the mailcontent
- The content of the mail
We then create a new message instance
And then finally build the message itself
Now at this point, the CampainReady
mailable is set. To use it, we go back to our send()
in the EmailController
and adjust it to this :
Notice that we are using Mail::queue
instead of Mail::send
.
We have to run the listen command on the queues before they can be dispatched:
php artisan queue:listen
In production, it is not advisable to use listen
because of it's high CPU usage. It is better we use work
and pass the --daemon option:
sudo nohup php artisan queue:work --daemon --tries=3
Building the Frontend
The Base Layout Our base layout looks like this :
We import bootstrap
and jquery
which we would be using for fronted styling and we also yield
our title
and content
which other templates that extend this layout would fill!
Create The Signup View
Create a blade template
for our signup
view. Lets call it signup.blade.php.
In the signup.blade.php
, we extend our base layout and then have a form that accepts the subscribers : First Name
, Last Name
and Email Address
Compose Page to Send Emails The compose
blade template is quite similar to the sign up . Our blade template looks like this :
We accept the title
and message
as form fields and then send it to the /send
route to handle the data as we have seen above.
Demo
Conclusion
In this article, we have seen how to create your own email platform using Laravel and Mailtrap’s SMTP server which has alot of applications in the real world. Here’s a link to the repository . For more review.