mailerlite/mailerlite-php
Official MailerLite PHP SDK for the MailerLite API v2. Manage subscribers, campaigns, groups, segments, fields, forms, automations, webhooks, timezones/languages, and batch requests. Includes tests and PHPStan support.
Installation:
composer require mailerlite/mailerlite-php
composer require php-http/curl-client guzzlehttp/psr7 php-http/message
Ensure your Laravel project has PSR-7 and PSR-18 support.
Configuration:
Add your MailerLite API key to .env:
MAILERLITE_API_KEY=your_api_key_here
Service Provider:
Register the SDK in config/app.php:
'providers' => [
// ...
MailerLite\MailerLiteServiceProvider::class,
],
Facade Usage: Publish the config (optional):
php artisan vendor:publish --provider="MailerLite\MailerLiteServiceProvider"
Use the facade in your code:
use MailerLite\Facades\MailerLite;
$subscriber = MailerLite::subscribers()->create(['email' => 'user@example.com']);
Create a subscriber and assign them to a group:
$subscriber = MailerLite::subscribers()->create([
'email' => 'user@example.com',
'fields' => ['name' => 'John Doe']
]);
$groupId = 123;
MailerLite::groups()->assignSubscriber($groupId, $subscriber['id']);
Create a dedicated service class to encapsulate MailerLite logic:
// app/Services/MailerLiteService.php
class MailerLiteService
{
public function __construct(protected MailerLite $mailerLite) {}
public function addSubscriberToGroup(string $email, string $groupId, array $fields = []): array
{
$subscriber = $this->mailerLite->subscribers()->create([
'email' => $email,
'fields' => $fields
]);
$this->mailerLite->groups()->assignSubscriber($groupId, $subscriber['id']);
return $subscriber;
}
}
Use Laravel events to trigger MailerLite actions:
// app/Listeners/SendWelcomeEmail.php
class SendWelcomeEmail
{
public function handle(Registered $event)
{
$subscriber = MailerLite::subscribers()->create([
'email' => $event->user->email,
'fields' => ['name' => $event->user->name]
]);
$campaignId = config('mailerlite.welcome_campaign_id');
MailerLite::campaigns()->schedule($campaignId, ['delivery' => 'instant']);
}
}
Leverage Laravel queues for bulk operations:
// app/Jobs/SyncUsersToMailerLite.php
class SyncUsersToMailerLite implements ShouldQueue
{
public function handle()
{
$users = User::where('email_verified_at', '!=', null)->get();
foreach ($users as $user) {
MailerLite::subscribers()->create([
'email' => $user->email,
'fields' => [
'name' => $user->name,
'user_id' => $user->id
]
]);
}
}
}
Create a controller to process MailerLite webhooks:
// routes/web.php
Route::post('/mailerlite/webhook', [MailerLiteWebhookController::class, 'handle']);
// app/Http/Controllers/MailerLiteWebhookController.php
class MailerLiteWebhookController extends Controller
{
public function handle(Request $request)
{
$payload = $request->json()->all();
$event = $payload['event'] ?? null;
if ($event === 'subscriber.created') {
$this->handleSubscriberCreated($payload['data']);
}
}
protected function handleSubscriberCreated(array $data)
{
// Logic to handle new subscriber
}
}
Create campaigns dynamically based on user actions:
// app/Services/CampaignService.php
class CampaignService
{
public function createWelcomeCampaign(string $userEmail, string $userName): array
{
$campaignData = [
'type' => 'regular',
'name' => 'Welcome Email for ' . $userName,
'language_id' => config('mailerlite.default_language_id'),
'emails' => [
[
'subject' => 'Welcome to Our Platform',
'from_name' => 'Support Team',
'from' => 'support@example.com',
'content' => "Hello {$userName}, welcome aboard!"
]
],
'filter' => [
'field' => 'email',
'operator' => 'equals',
'value' => $userEmail
]
];
return MailerLite::campaigns()->create($campaignData);
}
}
use Symfony\Component\HttpClient\Exception\TransportException;
try {
$response = $mailerLite->subscribers()->create($data);
} catch (TransportException $e) {
if ($e->getCode() === 429) {
sleep(1); // Wait and retry
return $this->createSubscriber($data);
}
throw $e;
}
public function handle(Request $request)
{
$payload = $request->json()->all();
$signature = $request->header('X-MailerLite-Signature');
if (!hash_equals(
$signature,
hash_hmac('sha256', $request->getContent(), config('mailerlite.webhook_secret'))
)) {
abort(403, 'Invalid signature');
}
// Process payload
}
$fieldName = 'user_id';
$fields = MailerLite::fields()->get();
if (!collect($fields)->contains('name', $fieldName)) {
MailerLite::fields()->create([
'name' => $fieldName,
'type' => 'text'
]);
}
delivery parameter carefully:
'instant' sends immediately.'scheduled' requires a date field (ISO 8601 format).$campaign = MailerLite::campaigns()->schedule($campaignId, [
'delivery' => 'scheduled',
'date' => now()->addHours(1)->toAtomString()
]);
$activity = MailerLite::campaigns()->getSubscriberActivity($campaignId, [
'type' => 'opened',
'filter' => ['email' => 'user@example.com']
]);
if ($activity['data'][0]['opened_at'] !== null) {
// User opened the email; trigger follow-up
}
$mailerLite = new MailerLite([
'api_key' => config('mailerlite.api_key'),
'debug' => true // Enable debug mode
]);
tap method to inspect responses:
$subscriber = MailerLite::subscribers()->create(['email' => 'test@example.com'])
->tap(function ($response) {
Log::debug('MailerLite response:', $response);
});
email for subscribers).email for lookups when possible (faster than fetching by ID).date fields in campaigns use UTC or a consistent timezone.$subscribers = MailerLite::subscribers()->get(['page' => 1, 'per_page' => 1000]);
// app/Services/MailerLiteTransport.php
class MailerLiteTransport implements Psr\Http\Message\RequestFactoryInterface
{
public function createRequest(string $method, $uri):
How can I help you explore Laravel packages today?