PHP code example of theihasan / laravel-mailerlite
1. Go to this page and download the library: Download theihasan/laravel-mailerlite library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
// Find subscriber by email
$subscriber = MailerLite::subscribers()
->email('[email protected]')
->find();
if ($subscriber) {
echo "Found: " . $subscriber['name'];
} else {
echo "Subscriber not found";
}
// Find subscriber by ID
$subscriber = MailerLite::subscribers()->findById('12345');
// Update subscriber by finding with email first
$updated = MailerLite::subscribers()
->email('[email protected]')
->named('Updated Name')
->withField('company', 'New Company')
->withField('role', 'Manager')
->active()
->update();
// Update subscriber by ID directly (if you already have the MailerLite ID)
$updated = MailerLite::subscribers()
->named('Direct Update')
->withField('last_updated', now()->toDateString())
->updateById('12345');
// Delete subscriber by finding with email first
$deleted = MailerLite::subscribers()
->email('[email protected]')
->delete(); // Returns true if deleted, false if not found
// Get total from the meta information when listing
$result = MailerLite::subscribers()->list(['limit' => 1]);
$total = $result['meta']['total'] ?? 0;
// Get active subscribers count
$result = MailerLite::subscribers()->list([
'filter[status]' => 'active',
'limit' => 1
]);
$activeCount = $result['meta']['total'] ?? 0;
// Get count by status
$unsubscribed = MailerLite::subscribers()->list([
'filter[status]' => 'unsubscribed',
'limit' => 1
])['meta']['total'] ?? 0;
$bounced = MailerLite::subscribers()->list([
'filter[status]' => 'bounced',
'limit' => 1
])['meta']['total'] ?? 0;
// Unsubscribe subscriber
$result = MailerLite::subscribers()
->email('[email protected]')
->unsubscribe();
// Resubscribe subscriber
$result = MailerLite::subscribers()
->email('[email protected]')
->resubscribe();
// Alternative: Update status directly
$result = MailerLite::subscribers()
->email('[email protected]')
->unsubscribed() // Sets status to 'unsubscribed'
->update();
$result = MailerLite::subscribers()
->email('[email protected]')
->active() // Sets status to 'active'
->update();
// Add existing subscriber to a group
$result = MailerLite::subscribers()
->email('[email protected]')
->addToGroup('group-id-123');
// Remove subscriber from a group
$result = MailerLite::subscribers()
->email('[email protected]')
->removeFromGroup('group-id-123');
// Add to multiple groups during creation
//https://dashboard.mailerlite.com/subscribers?rules=W1t7Im9wZXJhdG9yIjoiaW5fYW55IiwiY29uZGl0aW9uIjoiZ3JvdXBzIiwiYXJncyI6WyJncm91cHMiLFsiMTY0NjM3OTY3MjkyMzAyNjQxIl1dfV1d&group=164637967292302641
//This is your group id: &group=164637967292302641
$subscriber = MailerLite::subscribers()
->email('[email protected]')
->named('New User')
->toGroups(['group id', 'group id', 'group id'])
->subscribe();
// Get all groups
$groups = MailerLite::groups()->all();
// Get groups with filters
$groups = MailerLite::groups()->list([
'limit' => 50,
'page' => 1
]);
// Basic group creation
$group = MailerLite::groups()
->name('Newsletter Subscribers')
->create();
// Advanced group creation
$group = MailerLite::groups()
->name('VIP Customers')
->withDescription('High-value customers with premium access')
->create();
// Find group by ID
$group = MailerLite::groups()->find('group-id-123');
// Find group by name
$group = MailerLite::groups()->findByName('Newsletter Subscribers');
$updated = MailerLite::groups()
->name('Updated Group Name')
->withDescription('Updated description')
->update('group-id-123');
// Get subscribers in a group
$subscribers = MailerLite::groups()->getSubscribers('group-id-123', [
'limit' => 50,
'page' => 1
]);
// Add subscribers to group
$result = MailerLite::groups()->addSubscribers('group-id-123', [
'subscriber-id-1',
'subscriber-id-2'
]);
// Remove subscribers from group
$result = MailerLite::groups()->removeSubscribers('group-id-123', [
'subscriber-id-1'
]);
// Get all custom fields
$fields = MailerLite::fields()->all();
// Get fields with pagination
$fields = MailerLite::fields()->list([
'limit' => 25,
'page' => 1
]);
// Text field
$field = MailerLite::fields()
->name('company')
->asText()
->withTitle('Company Name')
->create();
// Number field
$field = MailerLite::fields()
->name('age')
->asNumber()
->withTitle('Age')
->lean()
->withTitle('Newsletter Subscription')
->withDefault(true)
->create();
// Select field with options
$field = MailerLite::fields()
->name('plan')
->asSelect(['basic', 'pro', 'enterprise'])
->withTitle('Subscription Plan')
->create();
// Find field by ID
$field = MailerLite::fields()->find('field-id-123');
// Find field by name
$field = MailerLite::fields()->findByName('company');
$updated = MailerLite::fields()
->withTitle('Updated Company Name')
->update('field-id-123');
// Get all campaigns
$campaigns = MailerLite::campaigns()->all();
// Get campaigns with filters
$campaigns = MailerLite::campaigns()->list([
'filter[status]' => 'sent',
'limit' => 25
]);
// ✅ Free Plan Compatible - Basic campaign (works on all plans)
$campaign = MailerLite::campaigns()
->subject('Weekly Newsletter')
->from('Newsletter Team', '[email protected]')
->html('<h1>Newsletter</h1><p>Content here...</p>')
->plain('Newsletter - Content here...')
->toGroups(['12345', '67890']) // Use group IDs or names (auto-resolved)
->forFreePlan() // Ensures compatibility with free plans
->create();
// ✅ Alternative - Explicit regular campaign
$campaign = MailerLite::campaigns()
->subject('Weekly Newsletter')
->from('Newsletter Team', '[email protected]')
->html('<h1>Newsletter</h1><p>Content here...</p>')
->regular() // Explicitly set as regular campaign
->toGroups(['12345', '67890'])
->create();
// Campaign with custom name
$campaign = MailerLite::campaigns()
->name('Weekly Newsletter Campaign') // Custom campaign name
->subject('Weekly Newsletter') // Email subject line
->from('Newsletter Team', '[email protected]')
->html('<h1>Newsletter</h1><p>Content here...</p>')
->toGroups(['newsletter-subscribers', 'customers']) // Group names auto-resolved
->create();
// Create and send immediately
$campaign = MailerLite::campaigns()
->subject('Breaking News')
->from('News Team', '[email protected]')
->html('<h1>Important Update</h1>')
->toGroup('subscribers')
->send();
// Create and schedule
$campaign = MailerLite::campaigns()
->subject('Weekend Sale')
->from('Sales Team', '[email protected]')
->html('<h1>50% Off Everything!</h1>')
->toSegment('active-customers')
->scheduleAt(now()->addDays(2))
->schedule();
// ⚠️ Growing Business/Advanced Plan Required
$campaign = MailerLite::campaigns()
->subject('A/B Test Newsletter')
->from('Team', '[email protected]')
->html('<h1>Version A</h1>')
->abTest([
'test_type' => 'subject',
'send_size' => 20
])
->toGroups(['subscribers'])
->create();
$campaign = MailerLite::campaigns()
->subject('Resend Campaign')
->from('Team', '[email protected]')
->html('<h1>Resend Content</h1>')
->resend() // Requires Growing Business or Advanced Plan
->toGroups(['subscribers'])
->create();
try {
$campaign = MailerLite::campaigns()
->subject('Test Campaign')
->from('Team', '[email protected]')
->html('<h1>Content</h1>')
->create();
} catch (\Ihasan\LaravelMailerlite\Exceptions\CampaignCreateException $e) {
if ($e->getCode() === 403) {
// Plan restriction - helpful guidance provided
echo $e->getMessage();
// Suggests alternatives like using regular campaigns or upgrading plan
}
}
// Find by MailerLite ID (if you have it)
$campaign = MailerLite::campaigns()->find('campaign-id-123');
// Find by campaign name (searches through all campaigns)
$campaign = MailerLite::campaigns()->findByName('Weekly Newsletter');
// Note: Due to MailerLite API limitations, campaigns don't have a direct
// "get by ID" endpoint, so find() searches through the campaign list
if ($campaign) {
echo "Found campaign: " . $campaign['name'];
} else {
echo "Campaign not found";
}
// This will throw a BadMethodCallException with helpful instructions:
try {
$segment = MailerLite::segments()
->name('Active Premium Users')
->whereField('plan', 'equals', 'premium')
->create();
} catch (\BadMethodCallException $e) {
echo $e->getMessage();
// "Segment creation is not supported by the MailerLite API.
// Segments must be created through the MailerLite web interface
// at https://dashboard.mailerlite.com/..."
}
// Find by MailerLite ID - searches through segment list
$segment = MailerLite::segments()->find('segment-id-123');
// Find by segment name (recommended approach)
$segment = MailerLite::segments()->findByName('Active Users');
// Note: MailerLite API doesn't have a single segment endpoint
// Both methods above search through paginated segment lists automatically
if ($segment) {
echo "Found segment: " . $segment['name'];
echo "Total subscribers: " . $segment['total'];
} else {
echo "Segment not found";
}
// Alternative manual approach (not recommended - use findByName instead)
$segments = MailerLite::segments()->all();
$targetSegment = collect($segments['data'])->firstWhere('name', 'Active Users');
// Only the segment name can be updated via API
$updated = MailerLite::segments()
->name('Updated Segment Name')
->update('segment-id-123');
// Note: Segment filters/conditions cannot be updated via API
// Use the MailerLite web interface to modify segment criteria
// Find by MailerLite ID - searches through automation list
$automation = MailerLite::automations()->find('automation-id-123');
// Find by automation name (recommended for better readability)
$automation = MailerLite::automations()->findByName('Welcome Series');
// Note: MailerLite API doesn't have a single automation endpoint
// Both methods search through paginated automation lists automatically
if ($automation) {
echo "Found automation: " . $automation['name'];
echo "Status: " . $automation['status'];
} else {
echo "Automation not found";
}
// Control automation state
MailerLite::automations()->startById('automation-id-123');
MailerLite::automations()->stopById('automation-id-123');
MailerLite::automations()->pauseById('automation-id-123');
MailerLite::automations()->resumeById('automation-id-123');
// Get automation analytics
$stats = MailerLite::automations()->stats('automation-id-123');
$activity = MailerLite::automations()->activity('automation-id-123');
$subscribers = MailerLite::automations()->subscribers('automation-id-123');
// Get all webhooks
$webhooks = MailerLite::webhooks()->all();
// Get webhooks with filters
$webhooks = MailerLite::webhooks()->list([
'limit' => 25
]);
use Ihasan\LaravelMailerlite\DTOs\SubscriberDTO;
use Ihasan\LaravelMailerlite\Facades\MailerLite;
test('subscriber can be created with fluent API', function () {
$subscriber = MailerLite::subscribers()
->email('[email protected]')
->named('Test User')
->withField('company', 'Test Corp')
->subscribe();
expect($subscriber['email'])->toBe('[email protected]');
expect($subscriber['name'])->toBe('Test User');
});
// ❌ These may fail on Free/Basic plans:
$campaign = MailerLite::campaigns()->abTest([...])->create(); // Requires Growing Business+
$campaign = MailerLite::campaigns()->resend()->create(); // Requires Growing Business+
// ✅ These work on all plans including Free:
$campaign = MailerLite::campaigns()->forFreePlan()->create(); // Free plan compatible
$campaign = MailerLite::campaigns()->regular()->create(); // Regular campaigns
$campaigns = MailerLite::campaigns()->all(); // View existing campaigns
$subscribers = MailerLite::subscribers()->all(); // Full subscriber management
// These methods automatically search through paginated lists:
// Campaign by name - searches through all campaigns
$campaign = MailerLite::campaigns()->findByName('Weekly Newsletter');
// Segment by name - searches through all segments
$segment = MailerLite::segments()->findByName('Active Users');
// Automation by name - searches through all automations
$automation = MailerLite::automations()->findByName('Welcome Series');
// Webhook by URL - searches through all webhooks
$webhook = MailerLite::webhooks()->findByUrl('https://app.example.com/webhook');
// These methods use the search functionality internally:
$campaign = MailerLite::campaigns()->find('campaign-id-or-name');
$segment = MailerLite::segments()->find('segment-id-or-name');
$automation = MailerLite::automations()->find('automation-id-or-name');
$webhook = MailerLite::webhooks()->find('webhook-id-or-url');
// More efficient - exact name match
$campaign = MailerLite::campaigns()->findByName('Weekly Newsletter');
// Less efficient - will search through many pages if not found early
$campaign = MailerLite::campaigns()->findByName('Newsletter That May Not Exist');
// Most efficient - direct API call (only works for Subscribers, Groups, Fields)
$subscriber = MailerLite::subscribers()->findById('12345');
$group = MailerLite::groups()->find('group-id-123');
$field = MailerLite::fields()->find('field-id-123');
// This will throw a helpful exception:
MailerLite::segments()->name('Test')->whereField('plan', 'premium')->create();
// BadMethodCallException: "Segments must be created through the MailerLite web interface..."
// Auto-generated name from subject
MailerLite::campaigns()->subject('Newsletter')->from('...')->create();
// Custom name
MailerLite::campaigns()->name('Campaign Name')->subject('Newsletter')->create();
// Both work the same way:
->toGroups(['12345', '67890']) // Group IDs
->toGroups(['Newsletter', 'Premium Customers']) // Group names (auto-resolved)
use Ihasan\LaravelMailerlite\Exceptions\{
CampaignNotFoundException,
SegmentNotFoundException,
AutomationNotFoundException,
WebhookNotFoundException
};
try {
$campaign = MailerLite::campaigns()->findByName('Non Existent Campaign');
// Returns null if not found
if (!$campaign) {
// Handle not found case
}
} catch (CampaignNotFoundException $e) {
// Handle specific campaign search errors
} catch (MailerLiteException $e) {
// Handle general API errors during search
}
// ✅ Good: Use specific, exact names for faster searches
$campaign = MailerLite::campaigns()->findByName('Weekly Newsletter - January 2024');
// ❌ Avoid: Generic names that might match multiple results
$campaign = MailerLite::campaigns()->findByName('Newsletter');
// ✅ Good: Cache results for frequently accessed resources
$segmentCache = cache()->remember('active-users-segment', 3600, function () {
return MailerLite::segments()->findByName('Active Users');
});
// ✅ Good: Handle not-found cases gracefully
$automation = MailerLite::automations()->findByName('Welcome Series');
if (!$automation) {
Log::warning('Welcome Series automation not found - may need to be recreated');
// Fallback logic here
}
// ✅ Good: Use direct ID methods when available (Groups, Fields, Subscribers)
$group = MailerLite::groups()->find('group-123'); // Direct API call
$field = MailerLite::fields()->find('field-456'); // Direct API call
$subscriber = MailerLite::subscribers()->findById('sub-789'); // Direct API call
use Ihasan\LaravelMailerlite\Exceptions\{
MailerLiteAuthenticationException,
SubscriberCreateException,
SubscriberNotFoundException,
CampaignCreateException,
SegmentCreateException
};
try {
// Your MailerLite operations here
} catch (MailerLiteAuthenticationException $e) {
// Handle authentication issues
} catch (SubscriberCreateException $e) {
// Handle subscriber creation failures
} catch (CampaignCreateException $e) {
// Handle campaign creation issues (missing name, invalid data, plan restrictions, etc.)
if (str_contains($e->getMessage(), 'advanced plan')) {
// Plan upgrade
// ❌ Plan-Related Campaign Errors
try {
$campaign = MailerLite::campaigns()
->subject('Newsletter')
->from('Team', '[email protected]')
->html('<h1>Content</h1>')
->abTest(['test_type' => 'subject']) // This stead
$campaign = MailerLite::campaigns()
->subject('Newsletter')
->from('Team', '[email protected]')
->html('<h1>Content</h1>')
->forFreePlan() // Use free plan compatible settings
->create();
}
}
// ✅ What works on all plans:
$subscribers = MailerLite::subscribers()->all(); // ✅ Subscriber management
$groups = MailerLite::groups()->all(); // ✅ Group management
$fields = MailerLite::fields()->all(); // ✅ Field management
$webhooks = MailerLite::webhooks()->all(); // ✅ Webhook management
$campaigns = MailerLite::campaigns()->all(); // ✅ View existing campaigns