Mailchimp newsletter subscription in Laravel
Udgivet 2018-05-17 - Skrevet af Philip Sørensen
As you may have noticed I have a newsletter you can sign up for on my website. If not, sign up here: ppsadk newsletter
. Newsletters are great for notifying your readers, and here I'll explain how to implement a simple Mailchimp newsletter in Laravel.
Spatie's Laravel and Mailchimp newsletterSpatie
is a Belgian software company that makes a lot of cool Laravel packages. Check out their collection here: Spatie's Laravel Packages
. One of them is Mailchimp integration, which enables you to do various tasks, such as subscriping an e-mail, directly from Laravel.
You install the newsletter package by running following commands in your Laravel directory:
The first command will install the package. The second command will publish the file newsletter.php
into your config directory. The config-file simply refers to the environment variables MAILCHIMP_APIKEY
The API key can be found on your Mailchimp account under Extras
, and then API keys
. The list ID can be found by clicking on your Mailchimp list, then Settings
, and then List name and defaults
. The list ID can then be found on the right.
Using the Newsletter package in your Laravel code
With the package installed what we want to do now, is to create a sign up form and the code that handles it. This requires two lines of code in the routes file, like so:
This of course requires a controller, so let's make it.
For the SubscribeShow
-function, what we'll do is just to return a view. A simple version of that view could look something like this:
object will be used to write a “Thank you for subscribing”-message, if it succeeds, and the errors will write if there were any errors with the form.
A form also requires a request handler, so we create one like this:
The request will be quite simple as anybody should be able to fill it out, and it only requires an e-mail.
Finally, the form needs to be handled in our NewsletterController. The Mailchimp integration is easily added with a use Newsletter;
in the top of the controller, and can be used relatively easy as shown here.
So a user visits the newsletter page and gets the view with the form. The form is filled out with an e-mail, and the SubscribeDo
-function subscribes the e-mail to the newsletter. The user is then returned to the view with a nice thank you message. Simple as that.
But wait, there's more
This was just a simple walkthrough of how you do simple e-mail subscription to your Mailchimp newsletter. If you are into more advanced stuff, the Spatie package actually enables you to get an instance of the underlying Mailchimp API, which is quite powerful. You can do it like this:
To learn more about this function please go to the Github here: spatie/laravel-newsletter Github
I hope you enjoyed this brief guide. Feel free to contact me
if you have any questions.
Der er ingen kommentarer.