Laravel Mailchimp Integration

Laravel Mailchimp API Integration: Step-by-Step Guide

Table of Contents

Email marketing continues to be a powerful tool for businesses looking to engage with their audience and drive conversions.

Mailchimp, a popular email marketing service, offers comprehensive features to create, manage, and analyze email campaigns.

Integrating the two is essential to harness the full potential of Mailchimp within your Laravel application.

Laravel, the elegant PHP framework known for its simplicity and expressive syntax, provides a seamless environment for building robust web applications.

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.

Need Professional Help?

Contact ClickySoft for professional Laravel Development Services for your next project. 

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

 

LARAVEL Mailchimp
  • 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

 

Laravel Mailchimp Integration
  • Next, go to settings, click on Audience name and Default
  • List the Audience name and defaults and copy the id provided
Laravel Mailchimp API Integration
  • 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:

laravel mailchimp

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.

 

Share:
Consult our Experts Now