spatie/statamic-mailcoach
Statamic addon for Mailcoach: view campaign and list summaries in the Statamic control panel, and automatically add subscribers from form submissions or newly registered users. Integrates Mailcoach data into your CMS workflow.
Installation:
composer require spatie/statamic-mailcoach
php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-config"
Configure Mailcoach:
.env:
MAILCOACH_API_KEY=your_api_key_here
First Use Case:
Control Panel > Mailcoach to see a summary of your campaigns and subscriber lists.subscribe helper in your form submission logic:
use Spatie\Mailcoach\Facades\Mailcoach;
Mailcoach::subscribe($email, $listId); // $listId is the Mailcoach list ID
public function handle()
{
$email = $this->data['email'];
Mailcoach::subscribe($email, 1); // Subscribe to list with ID 1
}
Verify Integration:
Subscriber Management:
subscribe and unsubscribe methods in form handlers, user registration, or API endpoints.
// Subscribe a user after registration
event(Registered::class, function ($user) {
Mailcoach::subscribe($user->email, config('mailcoach.lists.default'));
});
import method for large-scale subscriber additions (e.g., migrating from another system):
$emails = ['user1@example.com', 'user2@example.com'];
Mailcoach::import($emails, 1); // Import to list ID 1
Campaign Management:
trigger method to send campaigns programmatically (e.g., after an order is placed):
Mailcoach::trigger(1); // Trigger campaign with ID 1
getCampaigns method to fetch and display them in Statamic:
$campaigns = Mailcoach::getCampaigns();
Render them in a Statamic blade template:
@foreach($campaigns as $campaign)
<div>{{ $campaign->name }} (Status: {{ $campaign->status }})</div>
@endforeach
List Management:
createList method to dynamically manage lists (e.g., for segmented audiences):
$list = Mailcoach::createList([
'name' => 'Premium Users',
'description' => 'Users with premium subscriptions',
]);
$lists = Mailcoach::getLists();
Integration with Statamic Features:
users.created or users.updated events to sync subscribers:
event(Users\Events\UserCreated::class, function ($user) {
Mailcoach::subscribe($user->email, config('mailcoach.lists.default'));
});
<input type="hidden" name="mailcoach_list" value="{{ $listId }}">
Then handle it in your form handler:
$listId = $this->data['mailcoach_list'] ?? config('mailcoach.lists.default');
Mailcoach::subscribe($this->data['email'], $listId);
API-Driven Workflows:
// Example: Verify webhook signature in a Statamic route
$payload = request()->json()->all();
$signature = request()->header('X-Mailcoach-Signature');
if (Mailcoach::verifyWebhook($payload, $signature)) {
// Process webhook (e.g., update user status)
}
Statamic Blueprints:
fields:
mailcoach_campaign:
type: number
display: Mailcoach Campaign ID
help: ID of the Mailcoach campaign to trigger.
afterSave hook to trigger campaigns:
public function afterSave($model)
{
if ($model->mailcoach_campaign) {
Mailcoach::trigger($model->mailcoach_campaign);
}
}
Antlers Tags:
// In a service provider
Antlers::extend('mailcoachCampaigns', function ($expression) {
return Mailcoach::getCampaigns();
});
Usage in a template:
{{ mailcoachCampaigns }}
Scheduling:
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
Mailcoach::syncSubscribers(); // Custom method to sync
})->daily();
}
Testing:
Mailcoach::shouldReceive('subscribe')->once()->with($email, $listId);
$response = $this->post('/form', ['email' => 'test@example.com']);
$response->assertSessionHasNoErrors();
API Key Security:
.env and never commit it to version control.Rate Limiting:
try {
Mailcoach::import($emails, $listId);
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->getCode() === 429) {
sleep(2); // Wait before retrying
retry();
}
}
Subscriber Duplication:
if (!Mailcoach::isSubscribed($email, $listId)) {
Mailcoach::subscribe($email, $listId);
}
Time Zones and Scheduling:
$campaign->scheduled_at->setTimezone($user->timezone);
List Permissions:
Webhook Delays:
if (!$webhookProcessed) {
Mailcoach::pollForUpdates(); // Custom method to check for missed updates
}
Enable Logging:
mailcoach logging channel in config/logging.php to debug API interactions:
'channels' => [
'mailcoach' => [
'driver' => 'single',
'path' => storage_path('logs/mailcoach.log'),
'level' => 'debug',
],
],
mailcoach config:
'log_channel' => 'mailcoach',
API Response Inspection:
tap method to inspect raw API responses:
Mail
How can I help you explore Laravel packages today?