# Laravel

Use the ActivitySmith Laravel SDK to send Push Notifications and Live Activities from Laravel notifications, controllers, commands, and jobs.

Send Push Notifications and Live Activities to your iPhone from [Laravel](https://laravel.com). Use them as channels in your Laravel notifications, next to mail and Slack, or call the whole ActivitySmith API from controllers, commands, and jobs.

ActivitySmith sends to the devices paired to your own ActivitySmith account, so use it to tell you and your team what happens in your application. It doesn't reach your application's users.

Building with Laravel Rust? Use the [Laravel Rust SDK](/docs/sdks/laravel-rust) instead.

![Push Notification example for a new subscription event](https://cdn.activitysmith.com/features/new-subscription-push-notification.png)

## Installation

1. Add the package to your application. It needs Laravel 12 or 13:

   ```bash
   composer require activitysmith/laravel
   ```

2. [Create an API key](https://activitysmith.com/app/keys) and add it to `.env`:

   ```ini
   ACTIVITYSMITH_API_KEY=your-api-key
   ```

Laravel registers the service provider for you.

## Push Notifications

1. Return `PushNotificationChannel::class` from the `via` method of a notification.
2. Add a `toPushNotification` method that returns a `PushNotificationMessage`. It takes the same arguments as [`notifications->send()`](/docs/sdks/php#push-notifications) in the PHP SDK.
3. Send the notification, and say who receives it.

```php
namespace App\Notifications;

use ActivitySmith\Laravel\PushNotificationChannel;
use ActivitySmith\Laravel\PushNotificationMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class SubscriptionStarted extends Notification implements ShouldQueue
{
    use Queueable;

    public $tries = 3;

    public $backoff = 60;

    public function __construct(
        public string $plan,
        public int $amount,
    ) {}

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

    public function toPushNotification(object $notifiable): PushNotificationMessage
    {
        return new PushNotificationMessage(
            title: 'New subscription 💸',
            message: "{$this->plan} plan, \${$this->amount}/month",
            sound: 'coin',
            metadata: ['amount' => $this->amount],
        );
    }
}
```

`Recipients::everyone()` sends to every device in your ActivitySmith account:

```php
use ActivitySmith\Laravel\Recipients;
use App\Notifications\SubscriptionStarted;
use Illuminate\Support\Facades\Notification;

Notification::route('activitysmith', Recipients::everyone())
    ->notify(new SubscriptionStarted(plan: 'Pro', amount: 29));
```

`Recipients::channels('sales', 'customer-success')` sends to some of your [Channels](/docs/sdks/php#channels) instead.

To notify a model, add a `routeNotificationForActivitySmith` method to it. Return `null` to send nothing:

```php
namespace App\Models;

use ActivitySmith\Laravel\Recipients;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class Team extends Model
{
    use Notifiable;

    public function routeNotificationForActivitySmith(): ?Recipients
    {
        return $this->activitysmith_channel
            ? Recipients::channels($this->activitysmith_channel)
            : Recipients::everyone();
    }
}
```

Then call `$team->notify(new SubscriptionStarted(plan: 'Pro', amount: 29))`. Notify one team, not each of its users. Every notifiable sends its own Push Notification, so your devices would show one for each user.

With `$tries`, the queue tries again after a rate limit or an outage. It doesn't when ActivitySmith refuses the request, for example because no device is paired. After a timeout, a second try can send the same Push Notification twice.

## Live Activities

![Progress Live Activity showing percentage completion](https://cdn.activitysmith.com/features/progress-live-activity.png)

Live Activities stay on the Lock Screen and change as the work moves on. Inject the client to update one from a controller, a command, or a job. The first call with a stream key starts it, and later calls update it:

```php
namespace App\Jobs;

use ActivitySmith\ActivitySmith;
use ActivitySmith\LiveActivityContentState;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class ImportCustomers implements ShouldQueue
{
    use Queueable;

    public function handle(ActivitySmith $activitysmith): void
    {
        foreach ([0, 50, 100] as $percentage) {
            // Import some customers here...

            $activitysmith->liveActivities->stream(
                'customer-import',
                contentState: LiveActivityContentState::make(
                    title: 'Customer Import',
                    type: 'progress',
                    percentage: $percentage,
                ),
            );
        }

        $activitysmith->liveActivities->endStream('customer-import');
    }
}
```

Where you can't inject the client, get it with `app(ActivitySmith::class)`.

A notification can also update a Live Activity, through `LiveActivityChannel`. The recipients work the same way:

```php
namespace App\Notifications;

use ActivitySmith\Laravel\LiveActivityChannel;
use ActivitySmith\Laravel\LiveActivityMessage;
use ActivitySmith\LiveActivityContentState;
use Illuminate\Notifications\Notification;

class BackupStepFinished extends Notification
{
    public function __construct(public int $step) {}

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

    public function toLiveActivity(object $notifiable): LiveActivityMessage
    {
        return LiveActivityMessage::stream(
            'nightly-backup',
            contentState: LiveActivityContentState::make(
                title: 'Nightly Backup',
                type: 'segmented_progress',
                numberOfSteps: 3,
                currentStep: $this->step,
            ),
        );
    }
}
```

Return `LiveActivityMessage::end('nightly-backup')` to end it.

Queue workers can run jobs out of order. When updates follow each other quickly, leave out `ShouldQueue`, as in this example.

## Lock Screen Widgets

![Lock screen widgets](https://cdn.activitysmith.com/features/lock-screen-widgets.png)

Send a value to a metric key and see it in a widget on your Lock Screen. The first value creates the metric. For example, send it every hour from `routes/console.php`:

```php
use ActivitySmith\ActivitySmith;
use Illuminate\Support\Facades\Schedule;

Schedule::call(function (ActivitySmith $activitysmith) {
    $activitysmith->metrics->update('mrr', 12450);
})->hourly();
```

## App Icon Badge

![ActivitySmith app icon with an App Icon Badge](https://cdn.activitysmith.com/features/badge-count.png)

Show a number on your ActivitySmith app icon. Pass `0` to clear it:

```php
use ActivitySmith\ActivitySmith;

app(ActivitySmith::class)->badgeCount(8333);
```

## More of the API

The injected client is the [ActivitySmith PHP SDK](/docs/sdks/php). Its docs show every option, such as icons, buttons, sounds, and the other Live Activity types.

## Testing

Use `Notification::fake()` to check what your code sends:

```php
namespace Tests\Feature;

use ActivitySmith\Laravel\Recipients;
use App\Notifications\SubscriptionStarted;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

class SubscriptionTest extends TestCase
{
    public function test_a_new_subscription_sends_a_push_notification(): void
    {
        Notification::fake();

        // Run the code that starts a subscription...
        Notification::route('activitysmith', Recipients::everyone())
            ->notify(new SubscriptionStarted(plan: 'Pro', amount: 29));

        Notification::assertSentOnDemand(
            SubscriptionStarted::class,
            fn (SubscriptionStarted $notification, array $channels, object $notifiable) =>
                $notification->toPushNotification($notifiable)->title === 'New subscription 💸',
        );
    }
}
```

`Notification::fake()` doesn't cover calls to the injected client. Those go through Laravel's HTTP client, so use `Http::fake()` for them:

```php
use ActivitySmith\ActivitySmith;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;

Http::fake(['activitysmith.com/*' => Http::response(['success' => true])]);

app(ActivitySmith::class)->badgeCount(8333);

Http::assertSent(fn (Request $request) => $request['badge'] === 8333);
```

## Configuration

| Variable | Description | Default |
| --- | --- | --- |
| `ACTIVITYSMITH_API_KEY` | Your API key. Without it, the application starts and sending fails. | None |
| `ACTIVITYSMITH_TIMEOUT` | How long one request may take, in seconds. | `30` |

To change these in a config file instead, publish `config/activitysmith.php`:

```bash
php artisan vendor:publish --tag=activitysmith-config
```

## Additional Resources

### [Packagist](https://packagist.org/packages/activitysmith/laravel)

Install the ActivitySmith Laravel SDK from Packagist

### [Source Code](https://github.com/ActivitySmithHQ/activitysmith-laravel)

View the Laravel SDK source on GitHub
