Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mailerlite Php Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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.

  2. Configuration: Add your MailerLite API key to .env:

    MAILERLITE_API_KEY=your_api_key_here
    
  3. Service Provider: Register the SDK in config/app.php:

    'providers' => [
        // ...
        MailerLite\MailerLiteServiceProvider::class,
    ],
    
  4. 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']);
    

First Use Case: Subscriber Management

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']);

Implementation Patterns

1. Service Layer Integration

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;
    }
}

2. Event-Driven Workflows

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']);
    }
}

3. Batch Operations

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
                ]
            ]);
        }
    }
}

4. Webhook Handling

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
    }
}

5. Campaign Management

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);
    }
}

Gotchas and Tips

1. API Rate Limits

  • MailerLite enforces rate limits (e.g., 60 requests per minute).
  • Solution: Implement exponential backoff in your SDK wrapper:
    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;
    }
    

2. Webhook Verification

  • Always verify webhook payloads to prevent spoofing:
    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
    }
    

3. Field Management

  • Custom fields must be created before use. Check if a field exists first:
    $fieldName = 'user_id';
    $fields = MailerLite::fields()->get();
    
    if (!collect($fields)->contains('name', $fieldName)) {
        MailerLite::fields()->create([
            'name' => $fieldName,
            'type' => 'text'
        ]);
    }
    

4. Campaign Scheduling

  • Use delivery parameter carefully:
    • 'instant' sends immediately.
    • 'scheduled' requires a date field (ISO 8601 format).
    • Tip: Store scheduled dates in your database for debugging:
      $campaign = MailerLite::campaigns()->schedule($campaignId, [
          'delivery' => 'scheduled',
          'date' => now()->addHours(1)->toAtomString()
      ]);
      

5. Subscriber Activity Tracking

  • Track opens/clicks to personalize future campaigns:
    $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
    }
    

6. Debugging Tips

  • Enable SDK logging:
    $mailerLite = new MailerLite([
        'api_key' => config('mailerlite.api_key'),
        'debug' => true // Enable debug mode
    ]);
    
  • Use Laravel’s tap method to inspect responses:
    $subscriber = MailerLite::subscribers()->create(['email' => 'test@example.com'])
        ->tap(function ($response) {
            Log::debug('MailerLite response:', $response);
        });
    

7. Common Pitfalls

  • Missing Required Fields: Always validate required fields (e.g., email for subscribers).
  • ID vs. Email: Use email for lookups when possible (faster than fetching by ID).
  • Timezones: Ensure date fields in campaigns use UTC or a consistent timezone.
  • Batch Limits: MailerLite limits batch operations (e.g., 1000 subscribers per request). Use pagination:
    $subscribers = MailerLite::subscribers()->get(['page' => 1, 'per_page' => 1000]);
    

8. Extending the SDK

  • Create a custom transport layer for retries or logging:
    // app/Services/MailerLiteTransport.php
    class MailerLiteTransport implements Psr\Http\Message\RequestFactoryInterface
    {
        public function createRequest(string $method, $uri):
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity