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

Laravel Newsletter Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

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

  2. Choose a Driver:

    • Mailcoach: Set NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\MailcoachDriver and install spatie/mailcoach-sdk-php.
    • MailChimp: Set NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\MailChimpDriver and install drewm/mailchimp-api.
    • MailerLite: Set NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\MailerLiteDriver and install mailerlite/mailerlite-php.
  3. First Use Case: Subscribe a user to the default list:

    use Spatie\Newsletter\Facades\Newsletter;
    
    Newsletter::subscribe('user@example.com');
    

Implementation Patterns

Core Workflows

  1. Subscription Management:

    • Basic Subscription: Use subscribe() for one-time additions.
      Newsletter::subscribe('user@example.com');
      
    • Update or Subscribe: Use subscribeOrUpdate() to modify existing subscribers or add new ones.
      Newsletter::subscribeOrUpdate('user@example.com', ['first_name' => 'John']);
      
    • Unsubscribe: Remove a user from the list.
      Newsletter::unsubscribe('user@example.com');
      
    • Delete: Permanently remove a user (use sparingly; loses history).
      Newsletter::delete('user@example.com');
      
  2. List-Specific Operations: Specify a list name (configured in config/newsletter.php) to target a specific list:

    Newsletter::subscribe('user@example.com', listName: 'customers');
    
  3. Provider-Specific Attributes:

    • Mailcoach: Pass custom attributes (e.g., ['first_name' => 'John']).
    • MailChimp: Use merge variables (e.g., ['FNAME' => 'John']).
    • MailerLite: Use subscriber fields (e.g., ['name' => 'John']).
  4. Group/Interest Management (MailChimp): Subscribe users to specific groups/interests:

    Newsletter::subscribeOrUpdate(
        'user@example.com',
        ['FNAME' => 'John'],
        'customers',
        ['interests' => ['group1_id' => true]]
    );
    
  5. Subscriber Lookup: Check subscription status or fetch details:

    if (Newsletter::hasMember('user@example.com')) {
        $member = Newsletter::getMember('user@example.com');
    }
    

Integration Tips

  1. 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
    ]);
    
  2. Event-Driven Subscriptions: Trigger subscriptions via Laravel events (e.g., Registered):

    event(new Registered($user));
    // In event listener:
    Newsletter::subscribeOrUpdate($user->email, $user->toArray());
    
  3. API Access: Access the underlying API for advanced use cases:

    $api = Newsletter::getApi();
    $api->someCustomMethod(); // Provider-specific
    
  4. Testing: Use the NullDriver for local development/testing (set NEWSLETTER_DRIVER=Spatie\Newsletter\Drivers\NullDriver in .env).


Gotchas and Tips

Pitfalls

  1. Driver Configuration:

    • Ensure endpoint is null for MailChimp/MailerLite; only Mailcoach requires an endpoint.
    • Verify list.id matches the provider’s list/group ID (e.g., MailChimp’s list ID is not the same as its name).
  2. Attribute Naming:

    • MailChimp uses merge variables (e.g., FNAME, LNAME).
    • Mailcoach/MailerLite use custom fields (e.g., first_name).
    • Mismatched keys will fail silently or return unexpected results.
  3. Unsubscribe vs. Delete:

    • unsubscribe() marks users as inactive but retains history.
    • delete() removes users permanently (use only for GDPR compliance or data cleanup).
  4. Rate Limits:

    • MailChimp/MailerLite enforce API rate limits. Handle exceptions gracefully:
      try {
          Newsletter::subscribe('user@example.com');
      } catch (\Exception $e) {
          Log::error('Newsletter API error: ' . $e->getMessage());
      }
      
  5. List Name Ambiguity:

    • If no listName is provided, the package uses config('newsletter.default_list_name').
    • Omitting listName in multi-list setups may lead to unintended subscriptions.

Debugging

  1. API Errors:

    • For MailChimp, inspect errors with:
      Newsletter::getApi()->getLastError();
      
    • Log the raw API response for troubleshooting:
      \Log::debug('MailChimp API Response:', ['response' => $api->getLastResponse()]);
      
  2. NullDriver Quirks:

    • The NullDriver supports method chaining but does not persist data. Useful for testing but not production.
  3. Environment-Specific Issues:

    • Test .env configurations locally before deploying (e.g., NEWSLETTER_DRIVER=log to log API calls without hitting endpoints).

Extension Points

  1. 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,
    
  2. 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();
            }
        );
    }
    
  3. 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,
       ],
    ];
    
  4. Testing Utilities: Create a test double for the newsletter service:

    $this->mock(Newsletter::class)
        ->shouldReceive('subscribe')
        ->once()
        ->with('user@example.com');
    

Provider-Specific Tips

  1. Mailcoach:

    • Use UUIDs for list.id (found in Mailcoach’s list settings).
    • Leverage Mailcoach’s SDK for advanced features (e.g., campaigns, templates).
  2. MailChimp:

    • Group IDs are required for segmenting subscribers. Fetch them via the API:
      $groups = Newsletter::getApi()->getGroups();
      
    • Use campaigns and automations endpoints for marketing flows.
  3. MailerLite:

    • Groups are identified by group.id (not list.id). Ensure your config matches.
    • Use MailerLite’s webhooks for real-time subscriber updates.
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai