Search by

sendak / laravel

hesammousavi

Keeps your Laravel app's users and events in Sendak: contacts, events, queue, backfill.

dev-main 2026-11-29 13:12 UTC

This package is auto-updated.

Last update: 2026-11-29 13:16:18 UTC


README

Keeps your app's users and the things that happen to them in Sendak, so journeys (welcome, abandoned cart, thank-you) start by themselves. One-way: your app → Sendak's audience API (/v1/track/*). PHP 8.2+, Laravel 11, 12 or 13.

Install

composer require sendak/laravel
php artisan sendak:install        # publishes config/sendak.php and prints the steps
# .env:   SENDAK_KEY=...          a key of the "journeys" channel (create it in your Sendak account)
php artisan migrate               # three small tables: sendak_outbox, sendak_state, sendak_consents
php artisan sendak:ping           # checks the key, names the account
php artisan sendak:backfill       # sends everyone who already exists (never starts journeys)

If Packagist is slow or blocked from your server, use the mirror instead (same package, same files):

composer config repositories.sendak composer https://dl.sendak.ir/laravel
composer require sendak/laravel

Keep the scheduler running (* * * * * php artisan schedule:run): that is what sends. If you also run a queue worker, changes go out within seconds; without one they go out within a minute.

From then on, with no code: a user created or changed in App\Models\User becomes a Sendak contact (email, mobile, name, timezone, registered_at), Registered and Verified become the events user.registered and user.verified, and a deleted user is marked (see "What it cannot do").

What it does by itself, what it cannot

Automatic Needs your decision
User model → contact, on create/update/delete/restore Which business events matter: call Sendak::track() or map your own event classes in config
Email, Iranian mobile (Persian/Arabic digits too), first/last name (a single name is split), timezone Extra attributes: one line each in config, or a method on the model
Retries, batching, rate limits, pause on a refused key, health command Consent to marketing email: the package never guesses
Backfill of existing users, resumable

Customizing (least code first)

1. Config only (config/sendak.php, every value can come from .env). Several models, columns, extra attributes, exclusions:

'models' => [
    App\Models\User::class => [
        'columns'    => ['phone' => ['mobile', 'phone'], 'name' => 'full_name'],
        'attributes' => [
            'registered_at' => ['date', 'created_at'],
            'plan'          => ['string', fn ($u) => $u->subscription?->plan],
            'orders'        => ['number', 'orders_count'],
        ],
        'when'    => fn ($u) => ! $u->is_staff,                 // false skips the row
        'consent' => fn ($u) => $u->accepts_marketing ? 'granted' : null,
    ],
    App\Models\Lead::class => [],                                 // defaults are enough
],
'exclude' => ['domains' => ['mailinator.com'], 'emails' => ['boss@example.com']],

Closures in config break php artisan config:cache. Everywhere config takes a callback it also takes an invokable class ('when' => App\Sendak\IsStaff::class) or [App\Sendak\Mapper::class, 'method']; use those in production. The defaults contain no closures. (Checked with class names; config:cache itself was not run.)

2. On the model (trait; every method optional):

use Sendak\Laravel\Concerns\SyncsToSendak;

class Customer extends Model
{
    use SyncsToSendak;

    public function sendakShouldSync(): bool { return ! $this->is_bot; }
    public function sendakAttributes(): array { return ['score' => $this->score, 'vip' => $this->vip, 'since' => $this->created_at]; }
    public function sendakConsent(): ?string { return $this->agreed ? 'granted' : null; }
    // sendakContact(): array   → full control of email, phone, first_name, last_name, timezone, attributes
}

or a mapper class ('mapper' => App\Sendak\UserMapper::class, implementing Sendak\Laravel\Contracts\ContactMapper) if you do not want to touch the model.

3. Events with no code in the app — map Laravel's or your own events in config('sendak.events'):

'events' => [
    Illuminate\Auth\Events\Registered::class => ['name' => 'user.registered', 'once' => true],
    Illuminate\Auth\Events\Login::class      => ['name' => 'user.logged_in', 'every' => 21600], // at most one per 6 h per person
    App\Events\OrderPaid::class => ['mapper' => fn ($e) => [
        'contact'    => $e->order->user,                // a model, an email, or an array
        'name'       => 'order.paid',
        'id'         => "order-{$e->order->id}-paid",   // the same every time → never counted twice
        'entity_key' => (string) $e->order->id,
        'properties' => ['total' => $e->order->total, 'currency' => 'IRR'],
        'at'         => $e->order->paid_at,
    ]],
],

4. By hand

use Sendak\Laravel\Facades\Sendak;

Sendak::track($user, 'order.paid', ['total' => 120000], id: "order-$order->id-paid");   // user, email or array
Sendak::contact($user);                       // keep one person current
Sendak::sync(User::where('plan', 'pro'));      // after a mass update(), which fires no model events
Sendak::withoutSyncing(fn () => User::factory()->count(5000)->create());   // seeders, imports
Sendak::revokeConsent($user);                  // the person unsubscribed inside your app
Sendak::connection('shop')->track(...);        // another Sendak account (config sendak.connections)

Always pass an id that is the same each time the same thing is reported (an order's payment, not a random value): a retry, a double webhook or a re-run then never counts twice. Without an id each call is its own event.

5. Around it: Laravel events the package fires (ContactQueued, EventQueued, SendakBatchSent, SendakItemRejected, SendakAuthFailed) for your own alerting; app(Client::class), app(Outbox::class) are container bindings you can replace; Sendak::fake() records for your tests ($fake->assertEventTracked('order.paid'), assertContactQueued($email)); php artisan vendor:publish --tag=sendak-lang for your own wording of the command output (English and Persian are included).

Commands

sendak:ping checks the key and names the account (writes nothing)
sendak:backfill [Model] [--chunk=500] [--fresh] [--no-drain] sends everyone; stopped halfway, run it again and it resumes; never starts journeys
sendak:work [--max-time=50] sends what is waiting (the scheduler runs it every minute)
sendak:status [--json] queue size, failures by Sendak's code, whether the key works; --json for monitoring
sendak:retry-failed [--clear] puts failed rows back in line (or deletes them)
sendak:forget {email} removes what this package still holds locally about a person

Decisions that are easy to break (and why they are not options)

  • A person's id is a hash of the email (e_<sha256>), not the table's primary key: the same person on two of your apps, or a guest who registers later, stays one contact. A user with no email uses the mobile number (p_…), then u_<key>. Sendak cannot merge contacts, so this must never change once real data is in.
  • Attribute types are permanent in Sendak: the first value fixes a type, and a later value of another type is refused. Every value is converted to its declared type or dropped ("12" is never sent where a number is declared). Declare the type; do not rely on guessing.
  • Consent is only ever sent as granted, once. Sendak overwrites whatever it is sent, so repeating it on every save would undo an unsubscribe made in Sendak. Sendak::revokeConsent() is the one explicit way to send denied.
  • A backfill never starts journeys (emit_changes=false) and sends no past events: a welcome journey is for people who join from now on.
  • Your requests never wait for Sendak: observers only write to the outbox table, which lives in your own database connection by default, so a transaction your app rolls back leaves nothing behind (if you set outbox.connection to another database, that guarantee goes).
  • The key is write-only on Sendak's side. A deleted user therefore cannot be deleted in Sendak: the contact is marked (consent_email=denied, attribute deleted=true). Delete it in the panel if you must.
  • The key is read only from config/.env. It is never logged, stored in the outbox, or sent anywhere but your configured API address (https only; http is accepted just for localhost, .test and .local).

Trust

Composer checks the SHA-1 of a package against the one in packages.json. Packagist and dl.sendak.ir are both trusted over HTTPS only: there is no extra signature (unlike Sendak's WordPress plugin, which signs its updates). Pin the version in composer.lock and review updates like any dependency.

Tests

php tests/pure_test.php     # identity, phone, attribute typing, backoff, event names (no database)
php tests/outbox_test.php   # outbox + worker against a faked HTTP API, on MySQL
php tests/model_test.php    # models, events, facade, fake, backfill, commands, on MySQL
SENDAK_E2E_KEY=... php tests/e2e_test.php   # against a real running Sendak API (dev) on a private database
php bin/release.php ../sendak-downloads     # builds the zip and the Composer index for dl.sendak.ir/laravel

There is no Composer install inside this repo: the tests borrow the Laravel in ../sendak-api/vendor (Laravel 13, PHP 8.4), a skeleton app in tests/skel, and the dev MySQL of ../sendak-api (docker compose -f docker-compose.dev.yml up -d). They use a private database (sendak_test_laravel, override with TEST_DB) and drop it first.

Checked

Everything above under "Tests", including an end-to-end run against the real dev API: 900 users backfilled with the run killed after the first chunk and resumed (every person once, no event, types registered as declared), a live create and update, an event sent three times counted once, a refused attribute type parked on its own row while the others went in, a wrong key pausing sending without spending tries and a right key resuming by itself, and an unreachable Sendak waiting with backoff and delivering when it returned.

Not checked (be honest before relying on it)

  • Laravel 11 and 12, PHP 8.2 and 8.3: only Laravel 13 on PHP 8.4 ran. The code uses no syntax newer than 8.2 (searched), nothing more.
  • PostgreSQL, SQLite and MariaDB: the outbox uses portable calls (insertOrIgnore, a nullable unique key) but only MySQL 8 ran.
  • Octane, Horizon, queue workers on Redis/SQS: the flush job was checked only as "dispatched once per burst".
  • Multi-tenant packages (stancl/tenancy and the like): the outbox is an ordinary table of whichever database is current, which should work, but nothing ran. Set outbox.connection if tenants must share one outbox.
  • Cashier, Breeze, Fortify, Jetstream: not integrated on purpose (nothing here can be verified against them); map their events in config.
  • Persian text in the command output is a plain translation, read once, not reviewed by a second person.

Uninstall

composer remove sendak/laravel, then drop sendak_outbox, sendak_state and sendak_consents yourself (the migration's down() does it). Nothing in Sendak is removed.