Mailchimp Newsletter Form Integration To Laravel

March 26th, 2023

Let's create a form to subscribe to our newsletter first.

1<form action="{{ route('newsletter') }}" method="post">
2 @csrf
3 <div class="flex flex-col justify-center max-w-sm mx-auto text-gold">
4 <x-form.input type="text" name="email" placeholder="your.email@email.com" label="Your email:" class="text-center" />
5 <x-button type="submit" class="mt-8">Subscribe</x-button>
6 </div>
7</form>

Route

1Route::post('/newsletter', [NewsletterController::class, 'store'])->name('newsletter');

install mailchimp

1composer require mailchimp/marketing

sign in to mailchimp account, go to profile pic→account→extras→api keys: create API key

copy your API key to .env file in Laravel

1// .env
2 
3MAILCHIMP_KEY=your api key here

config/services.php add:

1'mailchimp' => [
2 'key' => env('MAILCHIMP_KEY'),
3 ]

NewsletterController

  • validate request: 'required|email' - email is required and must be formatted as an email address.

  • create new MailchimpMarketing\ApiClient()

  • mailchimp setConfig (apiKey, server)

  • add email and status to mailchimp lists: addListMember() to your list

  • define to which list you want to save this email: in config/services.php (list number from Mailchimp)

1'mailchimp' => [
2 'key' => env('MAILCHIMP_KEY'),
3 'lists' => [
4 'subscribers' => 'cbd7cb27b7',
5 ]
6]
1class NewsletterController extends Controller
2{
3 public function store()
4 {
5 request()->validate([
6 'email' => 'required|email'
7 ]);
8 
9 $mailchimp = new \MailchimpMarketing\ApiClient();
10 
11 $mailchimp->setConfig([
12 'apiKey' => config('services.mailchimp.key'),
13 'server' => 'us6'
14 ]);
15 
16 try {
17 
18 $response = $mailchimp->lists->addListMember(config('services.mailchimp.lists.subscribers'),[
19 'email_address' => request('email'),
20 'status' => 'subscribed'
21 ]);
22 
23 } catch (\Exception $e) {
24 throw ValidationException::withMessages([
25 'email' => "This email could not be added"
26 ]);
27 }
28 
29 return back()->with('success', 'Uspesno ste se narocili na novice! Hvala.');
30 
31 }
32}