spatie/laravel-newsletter
Laravel package to manage newsletter subscriptions across providers. Supports Mailcoach, MailChimp, and MailerLite, with a unified API for subscribing/unsubscribing and list management. Includes configurable integration via config/newsletter.php.
Installation:
composer require spatie/laravel-newsletter
php artisan vendor:publish --tag="newsletter-config"
Configure .env with your provider-specific credentials (e.g., NEWSLETTER_API_KEY, NEWSLETTER_LIST_ID).
Choose a Driver:
NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\MailcoachDriver and install spatie/mailcoach-sdk-php.NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\MailChimpDriver and install drewm/mailchimp-api.NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\MailerLiteDriver and install mailerlite/mailerlite-php.First Use Case: Subscribe a user to the default list:
use Spatie\Newsletter\Facades\Newsletter;
Newsletter::subscribe('user@example.com');
Subscription Management:
subscribe() for one-time additions.
Newsletter::subscribe('user@example.com');
subscribeOrUpdate() to modify existing subscribers or add new ones.
Newsletter::subscribeOrUpdate('user@example.com', ['first_name' => 'John']);
Newsletter::unsubscribe('user@example.com');
Newsletter::delete('user@example.com');
List-Specific Operations:
Specify a list name (configured in config/newsletter.php) to target a specific list:
Newsletter::subscribe('user@example.com', listName: 'customers');
Provider-Specific Attributes:
['first_name' => 'John']).['FNAME' => 'John']).['name' => 'John']).Group/Interest Management (MailChimp): Subscribe users to specific groups/interests:
Newsletter::subscribeOrUpdate(
'user@example.com',
['FNAME' => 'John'],
'customers',
['interests' => ['group1_id' => true]]
);
Subscriber Lookup: Check subscription status or fetch details:
if (Newsletter::hasMember('user@example.com')) {
$member = Newsletter::getMember('user@example.com');
}
Form Handling: Attach newsletter subscription to user registration/login forms:
// In a registration controller
Newsletter::subscribeOrUpdate($request->email, [
'first_name' => $request->first_name,
'last_name' => $request->last_name
]);
Event-Driven Subscriptions:
Trigger subscriptions via Laravel events (e.g., Registered):
event(new Registered($user));
// In event listener:
Newsletter::subscribeOrUpdate($user->email, $user->toArray());
API Access: Access the underlying API for advanced use cases:
$api = Newsletter::getApi();
$api->someCustomMethod(); // Provider-specific
Testing:
Use the NullDriver for local development/testing (set NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\NullDriver in .env).
Driver Configuration:
endpoint is null for MailChimp/MailerLite; only Mailcoach requires an endpoint.list.id matches the provider’s list/group ID (e.g., MailChimp’s list ID is not the same as its name).Attribute Naming:
FNAME, LNAME).first_name).Unsubscribe vs. Delete:
unsubscribe() marks users as inactive but retains history.delete() removes users permanently (use only for GDPR compliance or data cleanup).Rate Limits:
try {
Newsletter::subscribe('user@example.com');
} catch (\Exception $e) {
Log::error('Newsletter API error: ' . $e->getMessage());
}
List Name Ambiguity:
listName is provided, the package uses config('newsletter.default_list_name').listName in multi-list setups may lead to unintended subscriptions.API Errors:
Newsletter::getApi()->getLastError();
\Log::debug('MailChimp API Response:', ['response' => $api->getLastResponse()]);
NullDriver Quirks:
NullDriver supports method chaining but does not persist data. Useful for testing but not production.Environment-Specific Issues:
.env configurations locally before deploying (e.g., NEWSLETTER_DRIVER=log to log API calls without hitting endpoints).Custom Drivers: Extend the package by creating a custom driver:
namespace App\Newsletter\Drivers;
use Spatie\Newsletter\Drivers\Driver;
class CustomDriver implements Driver {
public function subscribe(string $email, array $attributes = []): void {
// Custom logic
}
// Implement other required methods
}
Register it in config/newsletter.php:
'driver' => App\Newsletter\Drivers\CustomDriver::class,
Service Provider Hooks: Override the default facade binding in your service provider:
public function register() {
$this->app->bind(
\Spatie\Newsletter\Facades\Newsletter::class,
function ($app) {
return new \App\Newsletter\CustomFacade();
}
);
}
Event Listeners:
Listen for newsletter events (e.g., Subscribed, Unsubscribed) to trigger side effects:
// In EventServiceProvider
protected $listen = [
\Spatie\Newsletter\Events\Subscribed::class => [
\App\Listeners\SendWelcomeEmail::class,
],
];
Testing Utilities: Create a test double for the newsletter service:
$this->mock(Newsletter::class)
->shouldReceive('subscribe')
->once()
->with('user@example.com');
Mailcoach:
list.id (found in Mailcoach’s list settings).MailChimp:
$groups = Newsletter::getApi()->getGroups();
campaigns and automations endpoints for marketing flows.MailerLite:
group.id (not list.id). Ensure your config matches.How can I help you explore Laravel packages today?