# Laravel

```bash
composer require watchtower15/laravel
php artisan vendor:publish --tag=wt15-config
```

The package is auto-discovered, and publishing is optional: every key but `metrics` has a default. Set the credentials you use in `.env`:

| Variable | Used for |
| --- | --- |
| `WT15_API_KEY` (`wt15ak_…`) | `Wt15::me()` and the REST API |
| `WT15_METRICS_TOKEN` (`wt15ms_…`) | Counting and listing custom metrics |
| `WT15_LOGS_TOKEN` (`wt15ls_…`) | Pushing log lines |
| `WT15_API_URL`, `WT15_INGEST_URL` | The two base URLs; leave them out for the defaults |
| `WT15_ENABLED` | `false` turns the bridge off |

Then run `php artisan wt15:test`. It needs Laravel 12 or 13 on PHP 8.3 or later.

## Count what your application does

Every metric key must be declared in `config/wt15.php`; a key that is not declared is never counted, so a typo cannot create a billable metric.

```php
'metrics' => [
    // a count per saved model
    'orders.shipped' => ['type' => 'count', 'on' => 'eloquent.created: App\Models\Shipment'],
    // a count per event, only when a condition holds
    'orders.refunded' => ['type' => 'count', 'on' => App\Events\OrderRefunded::class, 'when' => 'amount > 0'],
    // a count by an amount read from the event
    'orders.refunded_cents' => ['type' => 'count', 'on' => App\Events\OrderRefunded::class, 'value' => 'amount'],
    // a level written from your own code
    'queue.depth' => ['type' => 'level'],
],
```

A row has `type` (`count` or `level`), `on` (an event class, an `eloquent.<event>: <Model>` string, or a list), and optionally `when`, `value` and `after_commit`. `when` and `value` are a dot path read from the event, a literal, a comparison such as `amount > 0`, an invokable class, or `[Class::class, ...arguments]`. A malformed row is disabled, never thrown.

From your own code:

```php
use WatchTower15\Laravel\Facades\Wt15;

Wt15::increment('orders.shipped');
Wt15::gauge('queue.depth', 42);
Wt15::me();
Wt15::client()->ingest->metrics->list();
```

`increment()` and `gauge()` never throw. By default a count is written after the surrounding database transaction commits, so a rolled-back transaction counts nothing.

## Where the buckets live

Counts are kept in one bucket per metric key per minute in a Laravel cache store (`buffer.store`, the default store when null), which must increment atomically and give locks.

| Store |  |
| --- | --- |
| `redis` | Supported and tested |
| `database` | Supported on MySQL and PostgreSQL; refused on SQLite, the default of a new Laravel application |
| `memcached`, `dynamodb` | Supported, not tested by the package’s own suite |
| `file`, `apc`, `null`, `failover`, custom | Refused |
| `array` | Allowed under `APP_ENV=testing` only |

-   `cache:clear` and `optimize:clear` empty the default store, so with `buffer.store` null each deploy that runs them loses the open minutes’ counts. Keep the buffer in a store of its own.
-   Two applications on one cache store need distinct `buffer.prefix` values.

## Sending

**The scheduler (the default).** With `flush.schedule` true the bridge adds `wt15:flush --scheduled` to Laravel’s scheduler every minute, in the background and on one server. `--scheduled` always exits 0 whatever the run reports, so an outage never reaches your exception handler; the run’s one record and the heartbeat’s silence are the signals.

Where `php artisan schedule:run` is the main process of a container started each minute, the container stops when it returns and the background flush is killed. There, run `php artisan schedule:work`, or set `flush.schedule` to `false` and add the line yourself:

```php
Schedule::command('wt15:flush --scheduled')->everyMinute()->withoutOverlapping(5)->onOneServer();
```

**After the response.** With `flush.after_response` true, the first request of each minute flushes after the response is sent. It is for hosts with no scheduler. Under PHP-FPM the child that runs the flush serves nothing else until it ends: about 40 s at the defaults. A host with a small pool keeps the scheduler.

`flush.heartbeat` names a count key incremented in every flush, so a stopped pipe shows at WatchTower15 as silence an alarm can see.

## Logs

Add a channel to `config/logging.php`:

```php
'watchtower15' => [
    'driver' => 'watchtower15',
    'name' => 'my-app',                 // the stream name in WatchTower15
    'level' => env('WT15_LOG_LEVEL', 'warning'),
    'buffer_limit' => 100,              // lines held before a push during the request; 0 holds every line to the end
    'replace_placeholders' => true,
],
```

and put it in a stack (`LOG_STACK=single,watchtower15`) or use it alone. Lines are sent after the response, after each queue job and when a worker stops. On Laravel Vapor add a middleware that calls `Log::channel('watchtower15')->getLogger()->close()` after `$next($request)`. Log ingest takes 600 pushes a minute per token, so above about ten logging requests a second per token, lines are lost: raise the level, use a token per service, or use the agent’s file tail. See [logs](https://developer.watchtower15.com/sdks/php/logs/) for the breaker.

## Commands

| Command |  |
| --- | --- |
| `wt15:test` | Checks each configured credential: the API key with `me()`, the metric token with the source’s listing, the log token by its format |
| `wt15:metrics` | Lists the declared keys, the disabled rows with reasons, the store’s verdict and the pending error counters. `--diff` adds each key’s status at WatchTower15 |
| `wt15:flush` | One flush now. `--scheduled` is the scheduler’s form |

## Testing

```php
use WatchTower15\Laravel\Facades\Wt15;

$fake = Wt15::fake();

event(new OrderRefunded(amount: 5));

$fake->assertIncremented('orders.refunded');
```

`Wt15::fake()` records counters, gauges and API calls and sends nothing; a rolled-back transaction records nothing and an undeclared key is not recorded, as in production. See [testing your integration](https://developer.watchtower15.com/sdks/php/testing/).

## Octane and queue workers

The bridge holds no request state between requests, so no entry in `config/octane.php` is needed.

## Security

Credentials are read from `.env` and shown at most as their prefix and last four characters. The SDK never follows a redirect and sends credentials only to the two hosts you configure. Your `Http::globalOptions()` applies to the SDK’s requests: a global `verify` of `false` turns TLS verification off for them, and a global `debug` writes each request, `Authorization` header included, to its stream.

Source: https://developer.watchtower15.com/sdks/php/laravel/
