Larachimp: The Mailchimp steward for your Laravel project

By Diego | Dev Tutorials

Jul 03

This is a brief introduction to the latest addition to my Laravel set of tools: a Laravel Mailchimp API Client. Larachimp will aid your Mailchimp API integration efforts on your Laravel projects. Read on to learn how this can help you.

Yet another Mailchimp API Client for Laravel. Why?

“Why create yet another Mailchimp API client for Laravel? I’m sure there are plenty already”.

My initial motivation in creating this package was to help myself do this faster in my own projects. I’ve been integrating Mailchimp on several Laravel projects in the past, and I found myself doing the same thing over and over. Of course I used some help from other packages for it, but in some cases those packages introduced their own problems. I’m not going to go into any details of the issues here, but suffice to say that I was not happy dealing with additional problems from an external package not properly maintained.

As an additional bonus, I would be able to learn some more about Guzzle (the core dependency of this package) and play around with my own little child project, which I was looking forward from some time now.

What does Larachimp do?

My first objective with Larachimp was to make it a simple bridge between the Mailchimp API and a Laravel project. You can think of this almost like being a wrapper around the API, without the need to go into the ugly details of dealing with the low level API request directly.

So in this regard, Larachimp allows you to perform any of the Mailchimp API calls available in a simple way.

But this is not all. Larachimp aims to make your life easier and code less. From my own experience I found coding over and over the same workflow: A user registers and indicates that she wants to receive the website newsletter. The app then has to communicate with Mailchimp, and add this user to the corresponding list. Also, if the user later decides that she doesn’t want to receive the newsletter anymore, the app needs to go to Mailchimp again and “remove” the user email from the list. Larachimp will try to simplify this workflow for you as much as it can.

Let’s start from the basics, and then we can move forward to the more interesting and time saving features.

How to install Larachimp on your Laravel project?

The installation is pretty straightforward. If you are already using any other third party Laravel package you’ll be already familiar with the following steps (but if not, fear not. They are as simple as they look).

Add the following dependency to your composer.json:

// composer.json
{
  "require": {
    "diegocaprioli/larachimp": "~0.6"
  },
  "repositories": [
    {
      "type": "vcs",
      "url": "https://github.com/diegocaprioli/larachimp.git"
    }
  ]
}

Register the Larachimp service provider in your application. Add this to the providers array in your app.php file:

// config/app.php
 'providers' => [
     ...
     DiegoCaprioli\Larachimp\LarachimpServiceProvider::class
 ]

Add the Larachimp facade to your application. Add this to the aliases array in your app.php file:

// config/app.php
 'aliases' => [
     ...
     'LarachimpFacade' => DiegoCaprioli\Larachimp\LarachimpFacade::class
 ]

Publish the larachimp.php config file in your project, so you can tweak it to your own needs. On a command line console, go to your project’s root folder, and execute this:

php artisan vendor:publish

Configure Larachimp to your required list

Once you have published the configuration file, your project will end up with a new file in config/diegocaprioli/larachimp/larachimp.php. You can modify this file to suit your needs. The file is well documented. But very briefly, you will only need to set the api_key and list_id parameters to what corresponds to your Mailchimp account and desired list. You will find that information in your Mailchimp dashboard.

Basic API Requests

At it’s most basic level, Larachimp can help you make any Mailchimp API request. You can use any of the following methods to do so:

LarachimpFacade::get($resource, $options);

LarachimpFacade::post($resource, $options);

LarachimpFacade::patch($resource, $options);

LarachimpFacade::put($resource, $options);

LarachimpFacade::delete($resource, $options);

The $resource is a string specifying the Mailchimp resource you are communicating with. For example, if you want to get some list’s fields:

$response = LarachimpFacade::get('lists/01a4f2ac6m', [
    'query' => ['fields' => 'id,web_id,name'],
]);

The $resource you specify will be concatenated to the configured base_uri parameter in the larachimp.php configuration file. So please pay close attention on keeping the base_uri written with the final slash (/), and keep in mind to define any $resource string without any starting slash.

The $options is an array of request options, as accepted by the Guzzle Client request method. As you can see in the previous example, a ‘query’ options has been set (Guzzle Request option), and we specified that a ‘fields’ querystring parameter should be sent with the value ‘id,web_id,name’ (specific parameters accepted by the Mailchimp API List GET endpoint).

Advanced features

And now to the good stuff! Remember that at the beginning of this article I told you that what I really wanted was to write less code in each project. Larachimp also can take care of adding your application users to a Mailchimp list. Not only that, but it can remove them, or update their emails on the list when this happens on your application.

And all this in a very simple and quick way. You will need three things.

Properly configure the Mailchimp list ID

Make sure your list_id is set properly in the larachimp.php configuration file. This parameter is only used for the advanced features. If you only plan on using the Larachimp package for the basic requests, it’s safe to not set any value in the list_id parameter.

Implement the LarachimpListMember interface

Make your User class, or any class that has the list subscriber information on your application, implement the interface LarachimpListMember. This will allow the Larachimp package to know the email and name of the person you are synchronizing to Mailchimp. This interface is simple enough:

interface LarachimpListMember
{
  /**
   * Return the first name of the subscriber to the Mailchimp list 
   *
   * @return string 
   */    
   public function getFirstName();
   
  /**
   * Return the last name of the subscriber to the Mailchimp list
   *
   * @return string
   */
   public function getLastName();

  /**
   * Returns the current email of the subscriber to the Mailchimp list
   *
   * @return string
   */
   public function getEmail();

  /**
   * Returns true if the subscriber to the Mailchimp list wants to receive
   * emails sent to the list members.
   *
   * @return boolean
   */
   public function isSubscribedToMailchimpList();
 }
Dispatch the command to syncronize the user to Mailchimp

And finally, at the moment that your application requires to synchronize the user to the Mailchimp list (when the user is created or her “newsletter receiving choice” updated), you should be dispatching the proper command:

$this->dispatch(new SyncMailchimpMember($user));

This will queue a job that will take care of the synchronization. If you want to perform the request in a synchronous way and NOT use a queued job, you can also do that:

$manager = App::make(MailchimpManager::class);
$manager->syncMember($user);

Although the command and method uses the word synchronize, this is not completely correct. The data only travels from your application to Mailchimp. If any changes are performed on the Mailchimp side, Larachimip will do nothing at all. Furthermore, this can be even a problem for your application. If, for example, you manually change an email address of a subscriber on the Mailchimp side, Larachimp won’t be able to identify the user anymore, as the package currently uses the email address as the identifying information to perform the “synchronization”.

Another thing to note is that whenever the user decides (in your application) to stop receiving the “newsletter”, Larachimp will set the member on the list as “unsubscribed”. It will switch back and forth between the subscribed and unsubscribed status on the Mailchimp list depending on what value is returned by the isSubscribedToMailchimpList() method (required by the interface LarachimpListMember).

More features: Email address changes and complete subscriber removals.

Larachimp not only offers the synchronization method for your user. It can also deal with email address updates and completely removing a Mailchimp list member from the list. I don’t want to bore you to death nor make this article longer that what already is. The Larachimp package documentation is complete and will guide you to implement these other features. Fear not, they are as simple as the examples you already saw, and they follow the same pattern.

Final words

Larachimp will remain open source and free. I use it myself for several projects, so it will be kept under constant maintenance.

It won’t be strange to expect more features, so stay tuned. All the new versions released will be properly tagged and a brief change log entry will be added to explain the changes and additions. Any breaking change will be noted there too. And expect them to come in the future. this is a pretty young package and it will change over time for sure. Just keep your versions locked to a specific version and you’ll be ok. Check for updates periodically and the docs and change log will guide you on how to update your code.

Any suggestion or comments will be well received. If you think this package can be helpful, just give it a try and let me know what you think: https://github.com/diegocaprioli/larachimp.

Follow

About the Author

I’m a software engineer and work as an independent software developer and consultant. Software development is my passion. I usually find some time to write in between my work and my other interests, sports and PC gaming!