Play Video

Laravel Mailchimp API Integration: Step-by-Step Guide

Table of Contents

With Mailchimp, a leading email marketing service, you can access a comprehensive suite of features for effectively creating, managing, and analyzing email campaigns.

Integrating Mailchimp into your Laravel application is essential for maximizing its potential. Laravel, renowned for its elegant simplicity and expressive syntax, offers a seamless environment for developing robust web applications.

Explore the seamless integration of Mailchimp with Laravel to elevate your marketing efforts and effortlessly enhance audience engagement.

With the best Laravel packages and library ecosystem, it simplifies integrating third-party services like Mailchimp into your application. Find out why Laravel PHP framework is considered the best for development.

This article dives into the details of Laravel Mailchimp integration and shows you how to easily access Mailchimp’s data and functionality.

Whether you’re a developer looking to enhance your Laravel application or a business owner seeking to leverage the power of email marketing, this guide will equip you with the knowledge to utilize the Laravel MailChimp setting effectively.

What is Mailchimp in Laravel?

In Laravel, Mailchimp refers to the Mailchimp API integration with a Laravel application.

Mailchimp is a widely used and powerful platform that allows businesses to create, manage, and analyze email marketing campaigns.

It provides a range of features, including email template creation, subscriber management, campaign scheduling, advanced analytics, and automation tools.

When integrating Mailchimp with Laravel, developers can leverage the capabilities of Mailchimp directly within their application.

This integration enables seamless communication between the Laravel application and the Mailchimp API, allowing developers to programmatically access Mailchimp’s data and functionality.

Laravel provides a robust framework for integrating Mailchimp, offering various packages and libraries that simplify the integration process.

These packages provide convenient methods and classes to interact with the Mailchimp API, abstracting away the complexities of making API calls and handling responses.

After integrating Mailchimp with Laravel, businesses can streamline their email marketing processes.

They can automate tasks such as adding and removing subscribers, sending targeted email campaigns, and tracking the performance of their email marketing efforts.

This integration enhances the overall efficiency and effectiveness of email marketing strategies.

Laravel Help by Clickysoft

Boost your website with Clickysoft’s Laravel assistance. From simple to advanced, we’re here to make your ideas real. Let’s get started.

How to Use Mailchimp with Laravel - Laravel Mailchimp Settings

1. Start a New Project

The composer has to create a new project, “Create Project Laravel >> Laravel Mailchimp Demo 5.8”.

2. Set an Account for MailChimp

If you don’t already have one, sign up for a Mailchimp account at https://mailchimp.com/. Mailchimp offers a free plan with limited features, which is suitable for getting started.

  • Go to Profile >> Account >> Click on API Key

 

  • Click on Create API keys and copy the key generated
  • Now you must create a new List by clicking on the List in the menu and clicking on create new. After that, click on Audience

 

  • Next, go to settings, click on Audience name and Default
  • List the Audience name and defaults and copy the id provided
  • Finally, add the .env file.
				
					APP_ENV=local
APP_DEBUG=true
APP_KEY=HZoXrOanofcjLSbmF67kVtJyVHMFE3XU

DB_HOST=127.0.0.1
DB_DATABASE=learn
DB_USERNAME=root
DB_PASSWORD=root

MAILCHIMP_API_KEY=API Key Here
				
			

3. Installing Packages

The next step is to install skovmand/mailchimp-laravel package for Laravel Mailchimp transactional settings and API methods. First, the following command line has to be executed:

composer require skovmand/mailchimp-laravel

Next, we must use the config/app.php file to add the provider path and alias. Open the file and add the following lines:

				
					return [
	......
	$provides => [
		......
		......,
		Skovmand\Mailchimp\MailchimpServiceProvider::class,
	],
	.....
]
				
			

4. Adding routes

Let’s create three new routes as an example to enhance our understanding.

These routes will serve different purposes: one for the layout, another for subscribing users, and the last for sending campaigns.

Adding the following routes to your routes.php file allows us to delve into each functionality more effectively.

				
					App/Http/routes.php

Route::get('manageMailChimp', 'MailChimpController@manageMailChimp');
Route::post('subscribe',['as'=>'subscribe','uses'=>'MailChimpController@subscribe']);
Route::post('sendCompaign',['as'=>'sendCompaign','uses'=>'MailChimpController@sendCompaign']);

				
			

5. Adding Controllers

Proceeding with our example, we will introduce the MailChimpController file. You have two options: copy the entire controller file or copy and paste its contents into your project.

Both methods will enable you to utilize the functionalities demonstrated in the example effectively.

				
					App/Http/controllers/MailChimpController.php
namespace App\Http\Controllers;


use Illuminate\Http\Request;
use Auth;
use Config;


class MailChimpController extends Controller
{


    public $mailchimp;
    public $listId = '0e5ec5601as';


    public function __construct(\Mailchimp $mailchimp)
    {
        $this->mailchimp = $mailchimp;
    }


    public function manageMailChimp()
    {
        return view('mailchimp');
    }


    public function subscribe(Request $request)
    {
    	$this->validate($request, [
	    	'email' => 'required|email',
        ]);


        try {

        	
            $this->mailchimp
            ->lists
            ->subscribe(
                $this->listId,
                ['email' => $request->input('email')]
            );


            return redirect()->back()->with('success','Email Subscribed successfully');


        } catch (\Mailchimp_List_AlreadySubscribed $e) {
            return redirect()->back()->with('error','Email is Already Subscribed');
        } catch (\Mailchimp_Error $e) {
            return redirect()->back()->with('error','Error from MailChimp');
        }
    }


    public function sendCompaign(Request $request)
    {
    	$this->validate($request, [
	    	'subject' => 'required',
	    	'to_email' => 'required',
	    	'from_email' => 'required',
	    	'message' => 'required',
        ]);


        try {


	        $options = [
	        'list_id'   => $this->listId,
	        'subject' => $request->input('subject'),
	        'from_name' => $request->input('from_email'),
	        'from_email' => 'hardik@itsolutionstuff.com',
	        'to_name' => $request->input('to_email')
	        ];


	        $content = [
	        'html' => $request->input('message'),
	        'text' => strip_tags($request->input('message'))
	        ];


	        $campaign = $this->mailchimp->campaigns->create('regular', $options, $content);
	        $this->mailchimp->campaigns->send($campaign['id']);


        	return redirect()->back()->with('success','send campaign successfully');

        	
        } catch (Exception $e) {
        	return redirect()->back()->with('error','Error from MailChimp');
        }
    }


}

				
			

6. Addition of Blade File

The final step is to add a Blade file in the mailchimp.blade.php and copy the code given below:

				
					Resources/views/mailchimp.blade.php
@extends('layouts.app')

@section('content')
<h2 class="text-center">MailChimp API Example</h2>
<div class="container">

@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
	<button type="button" class="close" data-dismiss="alert">Ă—</button>	
        <strong>{{ $message }}</strong>
</div>
@endif


@if ($message = Session::get('error'))
<div class="alert alert-danger alert-block">
	<button type="button" class="close" data-dismiss="alert">Ă—</button>	
        <strong>{{ $message }}</strong>
</div>
@endif


	<div class="row">
		<div class="col-md-5">
			<div class="well">
	             {!! Form::open(array('route' => 'subscribe')) !!}
	              <div>
	              	<h3 class="text-center">Subscribe Your Email</h3>
	                 <input class="form-control" name="email" id="email" type="email" placeholder="Your Email" required>
	                 <br/>
	                 <div class="text-center">
	                 	<button class="btn btn-info btn-lg" type="submit">Subscribe</button>
	                 </div>
	              </div>
	             {!! Form::close() !!}
	    	 </div>
		</div>
		<div class="col-md-7">
			<div class="well well-sm">
          {!! Form::open(array('route' => 'sendCompaign','class'=>'form-horizontal')) !!}
          <fieldset>
            <legend class="text-center">Send Campaign</legend>

    
            <!-- Name input-->
            <div class="form-group">
              <label class="col-md-3 control-label" for="name">Subject</label>
              <div class="col-md-9">
                <input id="name" name="subject" type="text" placeholder="Your Subject" class="form-control">
              </div>
            </div>

    
            <!-- Email input-->
            <div class="form-group">
              <label class="col-md-3 control-label" for="email">To</label>
              <div class="col-md-9">
                <input id="email" name="to_email" type="text" placeholder="To " class="form-control">
              </div>
            </div>


            <!-- From Email input-->
            <div class="form-group">
              <label class="col-md-3 control-label" for="email">From</label>
              <div class="col-md-9">
                <input id="email" name="from_email" type="text" placeholder="From " class="form-control">
              </div>
            </div>

    
            <!-- Message body -->
            <div class="form-group">
              <label class="col-md-3 control-label" for="message">Your message</label>
              <div class="col-md-9">
                <textarea class="form-control" id="message" name="message" placeholder="Please enter your message here..." rows="5"></textarea>
              </div>
            </div>

    
            <!-- Form actions -->
            <div class="form-group">
              <div class="col-md-12 text-right">
                <button type="submit" class="btn btn-primary btn-lg">Send Campaign</button>
              </div>
            </div>
          </fieldset>
          {!! Form::close() !!}
        </div>
		</div>
	</div>
</div>
@endsection

				
			

Feeling overwhelmed?

ClickySoft offers you to Hire Laravel Developers with professional experience to make the integration seamless.

The Output

The image below shows the output generated after the Laravel Mailchimp integration process:

Bonus: How to Integrate Mailchimp with PHP?

Integrating MailChimp with PHP is almost the same as its Laravel integration counterpart. All you need to do is to follow some steps and rules to enhance its functionality. It is one of the PHP tips to leverage the power of the framework.

  • Sign up for a Mailchimp Account

If you haven’t done so, sign up for a Mailchimp account at https://mailchimp.com/. You’ll need an account to obtain your API key and access Mailchimp’s features.

  • Retrieve your Mailchimp API Key 

Once logged in to Mailchimp, go to your Account Settings. Under the Extras menu, select API keys. Generate or copy an existing API key for your integration.

  • Set up PHP Dependencies 

To interact with the Mailchimp API, you must install the mailchimp/marketing package using Composer. Run the following command in your project directory:

composer require mailchimp/marketing

  • Write Integration Code 

Create a PHP file and include the following code to initialize the Mailchimp client with your API key and perform basic integration operations:

				
					<?php

require 'vendor/autoload.php';

use MailchimpMarketing\ApiClient;

$apiKey = 'your-mailchimp-api-key';
$serverPrefix = 'your-mailchimp-server-prefix';

$apiClient = new ApiClient();
$apiClient->setConfig([
    'apiKey' => $apiKey,
    'server' => $serverPrefix,
]);

// Example: Fetch Lists
$response = $apiClient->lists->getAllLists();
$lists = $response->lists;

foreach ($lists as $list) {
    echo 'List Name: ' . $list->name . PHP_EOL;
    echo 'List ID: ' . $list->id . PHP_EOL;
    // Additional list details can be accessed here
}

// Example: Subscribe a User to a List
$response = $apiClient->lists->addListMember('your-list-id', [
    'email_address' => 'user@example.com',
    'status' => 'subscribed',
]);
echo 'Subscriber ID: ' . $response->id . PHP_EOL;
echo 'Subscriber Email: ' . $response->email_address . PHP_EOL;

// Additional Mailchimp API operations can be performed here

?>


				
			

Make sure to replace ‘your-mailchimp-api-key’ with your actual Mailchimp API key, and ‘your-mailchimp-server-prefix’ with the correct server prefix (e.g., “us1” or “us2”). You can find the server prefix in your Mailchimp account settings.

  • Run the Integration 

Save the PHP file and run it through a web server or the PHP CLI. The code provided demonstrates fetching lists and subscribing a user to a list, but you can explore other operations and methods provided by the Mailchimp API as well.

By following these steps, you can successfully integrate Mailchimp with PHP and begin leveraging its powerful email marketing capabilities within your application.

Conclusion

Integrating Mailchimp with Laravel brings together the power and benefits of the Laravel framework with the comprehensive email marketing features of Mailchimp. Following the steps outlined in this guide, you can seamlessly connect your Laravel application with Mailchimp and leverage its capabilities to enhance your email marketing efforts.

With Laravel Mailchimp integration, you can manage subscriber lists, create and send targeted email campaigns, track campaign performance, and automate various aspects of your email marketing strategy. This integration allows you to streamline your email marketing processes, increase engagement with your audience, and drive conversions effectively.

By integrating Mailchimp with Laravel, businesses can personalize their marketing communications, segment their audience, and deliver highly relevant content. This, in turn, helps to build stronger relationships with customers and maximize the effectiveness of email campaigns.

Clickysoft – Your Trusted Laravel Development Company

Clickysoft is dedicated to offering cutting-edge Laravel development services, employing the latest technologies and best practices to deliver superior results.

At Clickysoft, we are passionate about creating web solutions that are fast, secure, and scalable using the most advanced Laravel features and the best coding standards.

Our Laravel experts have years of experience and expertise in building custom web applications that meet your specific needs and exceed your expectations.

Whether you need a simple website or a sophisticated web application, we can deliver solutions that are tailored to your goals and challenges.

We have worked with clients from various industries and niches, such as finance, healthcare, e-commerce, and more, and helped them achieve amazing results with Laravel.

Don’t just take our word for it. Check out our portfolio and testimonials from our satisfied clients.

You will see why we are the ultimate Laravel development company.

Ready to take your web presence to the next level? Let’s collaborate and enhance your web presence with our Laravel expertise.

Share:
Consult our Experts Now

Request A Free Proposal

Great

Thank you for reaching out! We've received your message and will respond within 24 hours!

Exclusive Offer: 40 Hours of Free POC!

Don't leave without claiming your 40-hour Proof of Concept (POC) development. Let’s bring your project to life together!