PHP code example of x-laravel / listmonk

1. Go to this page and download the library: Download x-laravel/listmonk 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/ */

    

x-laravel / listmonk example snippets


use XLaravel\Listmonk\Contracts\NewsletterSubscriber;
use XLaravel\Listmonk\Traits\InteractsWithNewsletter;

class User extends Authenticatable implements NewsletterSubscriber
{
    use InteractsWithNewsletter;
}

class User extends Authenticatable implements NewsletterSubscriber
{
    use InteractsWithNewsletter;

    // Custom email column
    protected string $newsletterEmailColumn = 'email_address';

    // Custom name column
    public function getNewsletterNameColumn(): string
    {
        return 'full_name';
    }

    // Custom list IDs
    public function getNewsletterLists(): array
    {
        $lists = [1]; // Main newsletter

        if ($this->is_premium) {
            $lists[] = 2; // Premium list
        }

        return $lists;
    }

    // Custom attributes synced to Listmonk
    public function getNewsletterAttributes(): array
    {
        return [
            'plan' => $this->subscription_plan ?? '',
            'country' => $this->country ?? '',
            'registered_at' => $this->created_at?->toIso8601String(),
        ];
    }

    // Custom passive list per model
    public function getNewsletterPassiveListId(): ?int
    {
        return 5;
    }
}

use XLaravel\Listmonk\Facades\Listmonk;

// List subscribers
Listmonk::subscribers()->get(query: "subscribers.email LIKE '%@example.com%'");

// Find by ID
Listmonk::subscribers()->find(42);

// Create
Listmonk::subscribers()->create([
    'email' => '[email protected]',
    'name' => 'John Doe',
    'lists' => [1, 2],
    'status' => 'enabled',
    'preconfirm_subscriptions' => true,
]);

// Update
Listmonk::subscribers()->update(42, [
    'name' => 'Jane Doe',
    'lists' => [1, 2, 3],
]);

// Delete
Listmonk::subscribers()->delete(42);
Listmonk::subscribers()->deleteMany([42, 43, 44]);

// Manage lists
Listmonk::subscribers()->updateList(
    subscriberIds: [42, 43],
    listIds: [1, 2],
    action: 'add' // 'add', 'remove', or 'unsubscribe'
);

// Other operations
Listmonk::subscribers()->blocklist(42);
Listmonk::subscribers()->export(42);
Listmonk::subscribers()->bounces(42);
Listmonk::subscribers()->deleteBounces(42);
Listmonk::subscribers()->sendOptin(42);

Listmonk::lists()->get();
Listmonk::lists()->get(query: 'newsletter', status: 'enabled', minimal: true);
Listmonk::lists()->find(1);
Listmonk::lists()->create(['name' => 'My List', 'type' => 'public']);
Listmonk::lists()->update(1, ['name' => 'Updated List']);
Listmonk::lists()->delete(1);

// Sync a model (create or update in Listmonk)
Listmonk::newsletter()->sync($user);

// Partial update (only specified fields)
Listmonk::newsletter()->updatePartial($user, ['name']);

// Unsubscribe (delete from Listmonk)
Listmonk::newsletter()->unsubscribe($user);
Listmonk::newsletter()->unsubscribeByEmail('[email protected]');

// Move to passive list
Listmonk::newsletter()->moveToPassiveList($user, passiveListId: 5);
Listmonk::newsletter()->moveToPassiveListByEmail('[email protected]', passiveListId: 5);

// Batch sync
$results = Listmonk::newsletter()->syncMany(User::all());
// ['synced' => 95, 'failed' => 5, 'errors' => [...]]

listmonk()->subscribers()->find(42);
listmonk()->newsletter()->sync($user);

$user->subscribeToNewsletter();
$user->unsubscribeFromNewsletter();
$user->updateNewsletterSubscription();
$user->moveToPassiveList();

User::withoutNewsletterSync(function () {
    $user->update(['email' => '[email protected]']);
    // No Listmonk API calls will be made
});

use XLaravel\Listmonk\Events\SubscriberSubscribed;

class SendWelcomeEmail
{
    public function handle(SubscriberSubscribed $event): void
    {
        $model = $event->model;
        $apiResponse = $event->response;
    }
}

use XLaravel\Listmonk\Testing\InteractsWithListmonk;

class MyTest extends TestCase
{
    use InteractsWithListmonk;

    public function test_user_subscribes(): void
    {
        $this->fakeListmonk();

        $user = User::factory()->create();

        $this->assertSubscriberSynced($user->email);
    }

    public function test_with_existing_subscriber(): void
    {
        $this->fakeListmonkWithSubscriber([
            'id' => 1,
            'email' => '[email protected]',
            'name' => 'John',
            'lists' => [['id' => 1]],
            'attribs' => [],
            'status' => 'enabled',
        ]);

        // ...
    }

    public function test_api_failure(): void
    {
        $this->fakeListmonkFailure(500, 'Internal Server Error');

        // ...
    }
}
bash
php artisan vendor:publish --tag=listmonk-config
bash
# Check API connectivity
php artisan listmonk:health

# Sync all subscribers
php artisan listmonk:sync

# Sync a specific model
php artisan listmonk:sync "App\Models\Customer"

# With options
php artisan listmonk:sync --chunk=200 --force --dry-run