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 Setup

  1. Installation:

    composer require spatie/laravel-newsletter
    php artisan vendor:publish --tag="newsletter-config"
    
  2. Configure config/newsletter.php with your preferred driver (mailcoach, mailchimp, or mailerlite) and credentials. Example for Mailcoach:

    'driver' => Spatie\Newsletter\Drivers\MailcoachDriver::class,
    'driver_arguments' => [
        'api_key' => env('MAILCOACH_API_KEY'),
        'endpoint' => env('MAILCOACH_ENDPOINT'),
    ],
    'lists' => [
        'subscribers' => [
            'id' => env('MAILCOACH_LIST_UUID'),
        ],
    ],
    
  3. First Use Case: Subscribe a user to your default list:

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

Implementation Patterns

Core Workflows

  1. Subscription Management:

    • Basic Subscription:
      Newsletter::subscribe('user@example.com');
      
    • Subscription with Metadata (Mailcoach/MailerLite):
      Newsletter::subscribe('user@example.com', ['first_name' => 'John', 'last_name' => 'Doe']);
      
    • MailChimp Merge Variables:
      Newsletter::subscribe('user@example.com', ['FNAME' => 'John', 'LNAME' => 'Doe']);
      
    • Specific List:
      Newsletter::subscribe('user@example.com', listName: 'promotions');
      
  2. Updating Subscribers:

    Newsletter::subscribeOrUpdate('user@example.com', ['first_name' => 'UpdatedName']);
    
  3. Unsubscription:

    Newsletter::unsubscribe('user@example.com');
    

    Or for a specific list:

    Newsletter::unsubscribe('user@example.com', 'promotions');
    
  4. Deletion (use sparingly; removes all history):

    Newsletter::delete('user@example.com');
    
  5. Checking Subscriptions:

    if (Newsletter::hasMember('user@example.com')) {
        // Handle existing subscriber
    }
    
  6. MailChimp-Specific: Group Management:

    Newsletter::subscribeOrUpdate(
        'user@example.com',
        ['FNAME' => 'John', 'LAND' => 'US'],
        'subscribers',
        ['interests' => ['group_id_1' => true, 'group_id_2' => false]]
    );
    

Integration Tips

  • Laravel Events: Trigger newsletter actions in Registered or ProfileUpdated events:

    public function handle(Registered $event) {
        Newsletter::subscribe($event->user->email, [
            'first_name' => $event->user->first_name,
        ]);
    }
    
  • Forms: Use in registration/login forms or profile settings:

    <form method="POST" action="/subscribe">
        @csrf
        <input type="email" name="email" required>
        <button type="submit">Subscribe</button>
    </form>
    
  • API Endpoints: Expose subscription management via API:

    Route::post('/subscribe', function (Request $request) {
        Newsletter::subscribe($request->email, $request->attributes);
        return response()->json(['status' => 'subscribed']);
    });
    
  • Testing: Use the NullDriver for local development/testing:

    'driver' => Spatie\Newsletter\Drivers\NullDriver::class,
    

Gotchas and Tips

Pitfalls

  1. Driver-Specific Fields:

    • Mailcoach/MailerLite use attributes or fields.
    • MailChimp uses merge_vars (e.g., FNAME, LNAME).
    • Fix: Double-check field names for your provider.
  2. List IDs:

    • Mailcoach: UUID from the list settings.
    • MailChimp: List ID from MailChimp UI.
    • MailerLite: Group ID from Integrations > API.
    • Fix: Verify IDs in your provider’s dashboard.
  3. Unsubscription vs. Deletion:

    • unsubscribe() marks users as inactive but retains history.
    • delete() permanently removes users and history.
    • Fix: Use unsubscribe() unless you explicitly need deletion.
  4. Rate Limits:

    • MailChimp/MailerLite may throttle API calls.
    • Fix: Implement retries or batch processing for bulk operations.
  5. NullDriver Quirks:

    • Methods like getMember() return false (not null).
    • Fix: Use strict comparison (=== false) when checking responses.

Debugging

  • API Errors:

    • For MailChimp, inspect errors with:
      Newsletter::getApi()->getLastError();
      
    • Fix: Validate API keys and permissions in your provider’s dashboard.
  • Configuration Issues:

    • Ensure NEWSLETTER_DRIVER and NEWSLETTER_* env vars are set.
    • Fix: Run php artisan config:clear after updates.

Extension Points

  1. Custom Drivers: Extend Spatie\Newsletter\Drivers\Driver to support other providers:

    class CustomDriver implements Driver {
        public function subscribe(string $email, array $attributes = []): void {
            // Custom logic
        }
        // Implement other methods...
    }
    

    Register in config/newsletter.php:

    'driver' => App\Newsletter\Drivers\CustomDriver::class,
    
  2. Middleware: Add subscription checks in middleware:

    public function handle(Request $request, Closure $next) {
        if (!Newsletter::isSubscribed($request->user->email)) {
            abort(403);
        }
        return $next($request);
    }
    
  3. Service Providers: Bind custom logic to the Newsletter facade:

    public function boot() {
        Newsletter::extend(function ($app) {
            return new CustomDriver();
        });
    }
    

Performance Tips

  • Bulk Operations: Use provider-specific bulk endpoints (e.g., MailChimp’s lists/members batch operations) for large datasets.
  • Caching: Cache subscription checks if your lists change infrequently:
    $cached = Cache::remember("subscribed_{$email}", now()->addHours(1), function () use ($email) {
        return Newsletter::hasMember($email);
    });
    

Provider-Specific Notes

  • Mailcoach: Supports custom attributes and webhooks for real-time updates.
  • MailChimp: Requires interests to be pre-configured in lists for group management.
  • MailerLite: Groups are optional; subscribers can belong to multiple groups.
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony