> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Install the Courier skill before writing code: `npx skills add trycourier/courier-skills`. It carries the verified SDK shapes and the rules you cannot get wrong.
> Authenticate every request with `Authorization: Bearer <API_KEY>`. A workspace has several environments and each has its own keys, which are plain `pk_` strings with no environment prefix. Start with Test.
> Send with `client.send.message` from the Node SDK (`@trycourier/courier` v7 and later, where the client is the default import). Reference a template by its `nt_` id or its alias.
> A send accepts a bare Elemental element list, but storing content on a template requires the top-level elements wrapped in a channel element.
> To translate a template, write one locale at a time with `PUT /notifications/{id}/locales/{localeId}`, which merges into the existing translations. `PUT /notifications/{id}/content` and `PUT /notifications/{id}/elements/{elementId}` overwrite translations along with the content, so send each element's `id` and `locales` back, and first remove every `checksum` and any `locales` key that starts with an underscore.
> Templates and journeys can be built in the Courier app or created through the API. Either way they live in the workspace and are referenced by ID when you send.
> The hosted MCP server is https://mcp.courier.com. For a briefing on what Courier is and when to use it, read https://www.courier.com/llms.txt.
> Adding notifications to a framework app? Start from its quickstart, which has a runnable repo and complete files: Next.js email https://www.courier.com/docs/guides/add-transactional-email-to-nextjs.md, Django https://www.courier.com/docs/guides/add-notifications-to-django.md, Rails https://www.courier.com/docs/guides/add-notifications-to-rails.md, Node.js digest https://www.courier.com/docs/guides/batch-notifications-into-a-daily-digest-in-node.md, Laravel https://www.courier.com/docs/guides/add-notifications-to-laravel.md, FastAPI https://www.courier.com/docs/guides/send-notifications-from-fastapi.md, Express https://www.courier.com/docs/guides/add-notifications-to-express.md, and the React, Next.js, Astro, and Nuxt inbox quickstarts under /guides/add-an-inbox-to-*.
> Prefer the Guides tab for how-do-I questions and the Docs tab for how-does-it-behave questions. The API reference lives under /api-reference.

# Add notifications to a Laravel app

> Send Laravel notifications by email and SMS with Courier: a custom notification channel, queued after the transaction commits, with no duplicate sends.

Send email and SMS from a Laravel app by plugging Courier into Laravel Notifications as a custom channel. `$user->notify(new OrderShipped($order))` queues after the transaction commits, and one Courier call sends both.

```php theme={null}
<?php

require __DIR__.'/vendor/autoload.php';

$apiKey = getenv('COURIER_API_KEY') ?: throw new RuntimeException('Set COURIER_API_KEY');
$email = getenv('DEMO_EMAIL') ?: throw new RuntimeException('Set DEMO_EMAIL');

$response = (new Courier\Client(apiKey: $apiKey))->send->message(message: [
    'to' => ['email' => $email],
    'content' => ['title' => 'Hello from Laravel', 'body' => 'Your first Courier notification.'],
    'routing' => ['method' => 'single', 'channels' => ['email']],
]);

echo "Sent. Request id: {$response->requestID}\n";
```

Save it as `first_send.php`, then run it with your API key and email address:

```bash theme={null}
composer require trycourier/courier guzzlehttp/guzzle && COURIER_API_KEY=YOUR_COURIER_API_KEY DEMO_EMAIL=YOUR_EMAIL php first_send.php
```

It prints a request id to find in [Courier Logs](https://app.courier.com/logs). On a Test key, send to your Courier login address, which [test email](https://www.courier.com/docs/workspaces/environments.md#email-in-the-test-environment) reaches with no provider connected.

> [card] [courier-laravel-quickstart](https://github.com/trycourier/courier-laravel-quickstart)
>
> The finished Laravel app from this guide, ready to clone and run.

## Build this with a coding agent

To have a coding agent add Courier to your Laravel app, paste this prompt into Claude Code, Cursor, or Codex from the project root:

```text theme={null}
Add email and SMS notifications to this Laravel app with Courier.
Follow https://www.courier.com/docs/guides/add-notifications-to-laravel.md and the reference app at https://github.com/trycourier/courier-laravel-quickstart.
Use the trycourier/courier Composer package and read COURIER_API_KEY through config/services.php.
Add a custom notification channel that calls Courier, queue the notification with ShouldQueue and afterCommit, and pass the notification id as the idempotency key.
Send email and SMS in one send, and skip SMS when the user has no phone number.
When done, add a send command like the reference app's routes/console.php, run it, and show me the request id.
```

Install the Courier skill with `npx skills add trycourier/courier-skills`, and connect the [Courier MCP server](https://www.courier.com/docs/resources/mcp.md) so the agent can check Courier Logs and templates itself.

### Rules for AI agents

* Use `trycourier/courier` and `$client->send->message(message: [...], idempotencyKey: ...)` with camelCase keys, such as `userID`.
* Read `COURIER_API_KEY` through `config('services.courier.key')`, and call `env()` only inside `config/`.
* Return `CourierChannel` from `via()` and build the message in `toCourier()`.
* Implement `ShouldQueue` and call `$this->afterCommit()` in the notification's constructor.
* Pass the notification's `id` as `idempotencyKey`, and return `new CourierRetryPolicy` from `middleware()` to retry only [what Courier runs again](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).
* Never call Twilio or your mail provider directly, because Courier routes email and SMS.

## What you'll build

This Laravel app notifies a user through Courier when their order ships:

* **An email and a text** from one send, once the shipment commits
* **A `CourierChannel`** that any Laravel notification can use
* **Queue retries that never send twice**

Tested in November 2026 with Laravel 13.43, trycourier/courier 8.2.0, and PHP 8.5.

## Prerequisites

### For the first send

* [A Courier API key](https://app.courier.com/settings/api-keys)
* PHP 8.1 or newer and Composer

### For the full build

* PHP 8.3 or newer
* A Laravel 12 or newer app
* [A connected SMS provider, such as Twilio](https://www.courier.com/docs/integrations/sms/twilio.md)

## Clone the finished Laravel app

Clone the Courier Laravel quickstart to run the finished app with your own key:

```bash theme={null}
git clone https://github.com/trycourier/courier-laravel-quickstart.git
cd courier-laravel-quickstart
composer install
cp .env.example .env   # add your API key and DEMO_EMAIL
php artisan key:generate
touch database/database.sqlite
php artisan migrate
php artisan courier:send
```

The steps below add or change these files:

| File | What it does |
| - | - |
| `config/services.php` | Reads `COURIER_API_KEY` |
| `database/migrations/*_create_orders_table.php` | Adds `phone_number` and `orders` |
| `app/Models/User.php` | The Courier recipient |
| `app/Notifications/Channels/CourierChannel.php` | The Courier send |
| `app/Notifications/Channels/CourierRetryPolicy.php` | Picks which errors retry |
| `app/Notifications/OrderShipped.php` | The queued notification |
| `app/Models/Order.php` | Ships an order |

## Install the Courier PHP SDK in Laravel

The Courier PHP SDK is [`trycourier/courier`](https://www.courier.com/docs/sdk-libraries/php). Laravel already includes Guzzle, its HTTP client, so install only the SDK:

```bash theme={null}
composer require trycourier/courier
```

Add a `courier` entry to [`config/services.php`](https://github.com/trycourier/courier-laravel-quickstart/blob/main/config/services.php):

```php theme={null}
'courier' => [
    'key' => env('COURIER_API_KEY'),
    // Only `php artisan courier:send` reads these.
    'demo_email' => env('DEMO_EMAIL'),
    'demo_phone' => env('DEMO_PHONE'),
],
```

Read the key through `config()`, because `php artisan config:cache` stops Laravel loading `.env`. Add your key and address to `.env`, with an optional E.164 `DEMO_PHONE`:

```bash theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
DEMO_EMAIL=YOUR_EMAIL
DEMO_PHONE=
```

## Add a phone number and an orders table in Laravel

Courier's SMS channel needs the Laravel user's phone number. Run `php artisan make:model Order` and `php artisan make:migration create_orders_table`, then match the quickstart's [migration](https://github.com/trycourier/courier-laravel-quickstart/blob/main/database/migrations/2026_11_23_000000_create_orders_table.php):

> [accordion] database/migrations/\*\_create\_orders\_table.php
>
> ```php theme={null}
> <?php
>
> use Illuminate\Database\Migrations\Migration;
> use Illuminate\Database\Schema\Blueprint;
> use Illuminate\Support\Facades\Schema;
>
> return new class extends Migration
> {
>     public function up(): void
>     {
>         Schema::table('users', function (Blueprint $table) {
>             // E.164, such as +15551234567. Courier's SMS channel reads it.
>             $table->string('phone_number')->nullable();
>         });
>
>         Schema::create('orders', function (Blueprint $table) {
>             $table->id();
>             $table->foreignId('user_id')->constrained()->cascadeOnDelete();
>             $table->string('status')->default('placed');
>             $table->timestamps();
>         });
>     }
>
>     public function down(): void
>     {
>         Schema::dropIfExists('orders');
>
>         Schema::table('users', function (Blueprint $table) {
>             $table->dropColumn('phone_number');
>         });
>     }
> };
> ```

Run `php artisan migrate`. Then in [`app/Models/User.php`](https://github.com/trycourier/courier-laravel-quickstart/blob/main/app/Models/User.php), add `'phone_number'` to `$fillable` (`#[Fillable]` on Laravel 13) and these methods. Laravel channels look up the recipient with `routeNotificationFor<Channel>()`.

> [accordion] app/Models/User.php (additions)
>
> ```php theme={null}
> use Illuminate\Database\Eloquent\Relations\HasMany;
>
> public function orders(): HasMany
> {
>     return $this->hasMany(Order::class);
> }
>
> /**
>  * The Courier recipient for this user. Keep the same user_id everywhere
>  * you call Courier, so preferences and logs follow one person.
>  */
> public function routeNotificationForCourier(): array
> {
>     return array_filter([
>         'userID' => "user_{$this->id}",
>         'email' => $this->email,
>         'phoneNumber' => $this->phone_number,
>     ]);
> }
> ```

## Send email and SMS from a custom Laravel notification channel

A Laravel notification channel is a class with a `send()` method, and `CourierChannel` makes one Courier call to [`POST /send`](https://www.courier.com/docs/api-reference/send/send-a-message) per notification. The PHP SDK takes camelCase keys, such as `userID`, and sends them as snake\_case.

```php app/Notifications/Channels/CourierChannel.php lines theme={null}
<?php

namespace App\Notifications\Channels;

use Courier\Client;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Log;
use RuntimeException;

class CourierChannel
{
    /**
     * Send the notification through Courier and return Courier's request id.
     */
    public function send(object $notifiable, Notification $notification): string
    {
        $apiKey = config('services.courier.key')
            ?: throw new RuntimeException('Set COURIER_API_KEY in .env.');

        $courier = new Client(apiKey: $apiKey);

        $response = $courier->send->message(
            message: [
                // Who the user is to Courier: User::routeNotificationForCourier().
                'to' => $notifiable->routeNotificationFor('courier', $notification),
                ...$notification->toCourier($notifiable),
            ],
            // The notification's UUID survives queue retries, so a retry can't send twice.
            idempotencyKey: $notification->id,
        );

        Log::info("Courier accepted notification {$notification->id} as {$response->requestID}");

        return $response->requestID;
    }
}
```

## Limit Laravel queue retries to connection errors and rate limits

`CourierRetryPolicy` lets the Laravel queue retry only the [errors Courier runs again](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely) for the same idempotency key, and fails the job on any other.

> [accordion] app/Notifications/Channels/CourierRetryPolicy.php
>
> ```php app/Notifications/Channels/CourierRetryPolicy.php lines theme={null}
> <?php
>
> namespace App\Notifications\Channels;
>
> use Courier\Core\Exceptions\APIConnectionException;
> use Courier\Core\Exceptions\ConflictException;
> use Courier\Core\Exceptions\RateLimitException;
> use Throwable;
>
> /**
>  * Queue middleware: fail at once on any error Courier would replay for the same key.
>  */
> class CourierRetryPolicy
> {
>     public function handle(object $job, callable $next): mixed
>     {
>         try {
>             return $next($job);
>         } catch (APIConnectionException|RateLimitException|ConflictException $e) {
>             // The queue retries with the same key, after $backoff.
>             throw $e;
>         } catch (Throwable $e) {
>             // No retries. The job goes to failed_jobs with this error.
>             $job->fail($e);
>
>             throw $e;
>         }
>     }
> }
> ```

## Queue the Laravel notification after the transaction commits

`OrderShipped` is a standard Laravel notification that `via()` routes to Courier through `CourierChannel`, and `middleware()` adds the retry policy.

```php app/Notifications/OrderShipped.php lines theme={null}
<?php

namespace App\Notifications;

use App\Models\Order;
use App\Notifications\Channels\CourierChannel;
use App\Notifications\Channels\CourierRetryPolicy;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class OrderShipped extends Notification implements ShouldQueue
{
    use Queueable;

    // CourierRetryPolicy fails the job at once on any error Courier would replay.
    public $tries = 5;

    // Courier holds the key for 60 seconds, so the first retry waits that long.
    public $backoff = [60, 120, 300];

    public function __construct(public Order $order)
    {
        // Queue only after the shipping transaction commits, so a rollback notifies nobody.
        $this->afterCommit();
    }

    public function via(object $notifiable): array
    {
        return [CourierChannel::class];
    }

    public function middleware(object $notifiable, string $channel): array
    {
        return [new CourierRetryPolicy];
    }

    /**
     * The Courier message, without `to`. CourierChannel adds the recipient.
     */
    public function toCourier(object $notifiable): array
    {
        return [
            'content' => [
                'title' => "Order #{$this->order->id} has shipped",
                // Courier links this user's hosted preference page, because the send has a user_id.
                'body' => "Your order is on its way.\n\nChoose what we send you: {{var \"urls.preferences\"}}",
            ],
            'routing' => [
                // `all` sends every channel listed. `single` would stop at the first one that works.
                'method' => 'all',
                // Skip SMS for a user with no phone number.
                'channels' => $notifiable->phone_number ? ['email', 'sms'] : ['email'],
            ],
            'data' => ['order_id' => $this->order->id],
        ];
    }
}
```

## Ship an order and notify the user in Laravel

`markShipped()` writes the status and calls `notify()` in one Laravel transaction, so a rolled-back shipment queues no Courier send.

```php app/Models/Order.php lines theme={null}
<?php

namespace App\Models;

use App\Notifications\OrderShipped;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\DB;

class Order extends Model
{
    protected $fillable = ['status'];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Mark the order shipped and notify its user once the change commits.
     */
    public function markShipped(): void
    {
        DB::transaction(function () {
            // Start from the stored row, so a retry after a rollback writes the status again.
            $this->refresh();
            $this->update(['status' => 'shipped']);

            // Each call gets a new notification id, so shipping again later notifies again.
            $this->user->notify(new OrderShipped($this));
        });
    }
}
```

Call `$order->markShipped()` from a controller or job, and run a worker for Laravel's default `database` queue:

```bash theme={null}
php artisan queue:work
```

## Verify

Ship one order and find it in Courier. In the cloned repo, [`php artisan courier:send`](https://github.com/trycourier/courier-laravel-quickstart/blob/main/routes/console.php) does it on the `sync` queue and prints the request id:

```text theme={null}
Courier request id: 1-6740a1b2-...
Shipped order #1 for user_123. See it in https://app.courier.com/logs
```

In your own app, start `php artisan queue:work`, then run `App\Models\Order::first()->markShipped()` in `php artisan tinker`. The worker writes the request id to `storage/logs/laravel.log`. Open it in [Courier Logs](https://app.courier.com/logs) to see each channel and provider. A user with no phone number gets email only.

| What you see | Fix |
| - | - |
| `Set COURIER_API_KEY in .env.` | Add the key, then run `php artisan config:clear` and `php artisan queue:restart` |
| Nothing sends from your app | Run `php artisan queue:work` |
| SMS is [`UNROUTABLE`](https://www.courier.com/docs/send/statuses#why-a-message-is-unroutable) | Connect an SMS provider and use E.164 |

## Go to production with Courier

Courier is notification infrastructure for humans and AI agents. [Go live](https://www.courier.com/docs/guides/go-live.md) moves your Laravel app from Test to Production:

* **Switch keys.** Set a Production `COURIER_API_KEY` and connect your providers in that environment.
* **Keep a worker up.** Run `queue:work` under Supervisor or Laravel Horizon, or queued notifications never send.
* **Honor opt-outs.** Add `'preferences' => ['subscriptionTopicID' => ...]` to the message so the hosted page's choices apply.

| Task | Laravel's built-in channels | With Courier |
| - | - | - |
| Provider failover | The `failover` mailer, for email | [Failover](https://www.courier.com/docs/send/routing.md#failover) on every channel |
| User preferences | A table and settings screen | A [topic](https://www.courier.com/docs/recipients/preferences/overview.md) and hosted page |
| Change the copy | Edit a view and deploy | A [template](https://www.courier.com/docs/design/templates/overview.md) your team edits |
| One log | Each provider's dashboard | [Logs](https://www.courier.com/docs/monitor/logs.md) across channels |

## FAQ

> [accordion] Should I use Laravel Notifications or Courier?
>
> Laravel Notifications and Courier work together, because Courier is one more channel in `via()`. Keep `mail` and `database`, and route SMS, failover, and hosted preferences through `CourierChannel`.

> [accordion] How do I send SMS from Laravel?
>
> Laravel sends SMS through Courier when the recipient has an E.164 `phoneNumber` and `routing.channels` includes `sms`. Connect an SMS provider such as [Twilio](https://www.courier.com/docs/integrations/sms/twilio.md) in Courier first.

> [accordion] Do I need a queue worker to send notifications from Laravel?
>
> Laravel runs queued Courier notifications only while `php artisan queue:work` runs. With `QUEUE_CONNECTION=sync`, Laravel sends inline after the commit with no retry, so a failed send throws from `markShipped()` after the order is saved.

> [accordion] How do I stop duplicate notifications when a queued job retries?
>
> Laravel queue retries can't duplicate a Courier notification, because the notification's `id` is the idempotency key. `CourierRetryPolicy` fails the job on any error Courier would [replay for that key](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).
