How to Mailchimp api integration in Laravel ?

Today now in this post i will show you How to Mailchimp api integration in Laravel ? Here we will learn how we can integrate mailchimp api in our laravel application. Mailchimp provides us manage subscribers, send emails by using campaign and also track the email results etc. By using Mailchimp we can track how much subscribers are open email and read. If we have newsletter website or any other tutorial website then we should add the email subscriber function on that way we can inform through by email.

Here i will use skovmand/mailchimp-laravel package for the mailchimp api in laravel application. So now in this example we will know about how to subscriber email and how we send campaign from laravel application from the scratch, so if we don’t know how to do. Hope it’s very simple to do this example. 

Step 1: Create MailChimp Account Setting

If you don’t have any account then we need to create a new account from here : Create New Account.

Okay, now we need to create a new List, click on Lists on the menu and then create a new list. So after the create successfully lists then select your list, then we get to settings->List name and defaults and then copy our list id, we will use it on api.

Okay now we can get the API Key so click here and get the api key : API Key

Open your .env file and paste here this way:

.env

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
Step 2: Install Package

Okay now in this step we need to install skovmand/mailchimp-laravel package for using MailChimp api methods. So at first need to fire the bellow command in your cmd or terminal:

composer require skovmand/mailchimp-laravel

Now we have to add the provider path and alias path in config/app.php file so need to open that file and add the bellow code.

config/app.php

return [
	......
	$provides => [
		......
		......,
		Skovmand\Mailchimp\MailchimpServiceProvider::class,
	],
	.....
]
Step 3: Add Route

Now in this step we need to add new three route for the creating small example on that way we can understand very well. Here one is for layout, second one is for subscribe and last one is for send campaign. So first add the bellow route in our routes.php file.

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']);
Step 4: Add Controller

So now in this step we have to add MailChimpController file for our this example. Then we can copy the whole controller file then also we can just need to copy and paste.

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');
        }
    }
}
Step 5: Add Blade file

Hope now we are in last step and we have to just need to create new blade file as name mailchimp.blade.php and then put the bellow code on that file.

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

Read Also : Laravel 8 Mobile Number Verification Tutorial

Thanks for read. I hope it help you. For more you can follow us on facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →