---
title: "Push Notifications"
description: "Send push notifications to your app's phones from Laravel, through Firebase Cloud Messaging on Android and the Apple Push Notification service on iOS."
---

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

# Push Notifications

## Introduction

Push notifications reach your users when the app isn't open. Your app registers its phone for push from JavaScript and sends the token to your server. Laravel then sends each notification through a `Push` notification channel, which uses Firebase Cloud Messaging on Android and the Apple Push Notification service, or APNs, on iOS.

> **Early release**
>
> Lairport is at v0.1. The `laravel-mobile` CLI is published on crates.io, and the `@laravel-rust-mobile/core` adapter is published on npm. Each feature is in beta or alpha: beta features are ready to try on your own apps, and alpha features are experimental. The [status](https://docs.lairport.app/status/) page lists the stage of each feature.

## Installing Push Notifications

If you would like to add push notifications to an existing app, run the `install` command with the feature's name:

```sh
laravel-mobile install push-notifications
```

The command sets `push-notifications = true` under `[plugins]` and `notifications = true` under `[permissions]` in your `mobile.toml`, then runs `sync`. If you are setting up a new app, you may pass the same feature to `init` with `--with push-notifications` instead.

## Adding Firebase for Android

Android phones receive push through Firebase. In the Firebase console, open your project's Android app, download its `google-services.json` file, and save it as `resources/mobile/google-services.json`. The app builds without this file, but Android phones can't receive push notifications until it exists.

iOS doesn't use Firebase, so the APNs settings below are all it needs.

### The Notification Icon

Android shows only the shape of a notification's small icon, in one colour. `laravel-mobile sync` draws it for you from your app icon: whatever differs from the icon's background colour becomes the white shape. If your icon is a photo or a gradient, save your own white-on-transparent PNG as `resources/mobile/notification-icon.png` and run `laravel-mobile sync` again.

## Registering a Phone

Call `mobile.push.register()` from your JavaScript after the user logs in. It asks the user to allow notifications, unless they already have, and then resolves a `{ token, platform }` object to send to your server. It resolves `null` if the user says no, or if the page isn't running in the phone app:

```js
const device = await mobile.push.register();

if (device) {
    await fetch('/devices', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(device),
    });
}
```

Call it on every launch, not once. Tokens change when the app is reinstalled or the phone is restored, so store the latest one each time. When the user logs out, call `mobile.push.unregister()` so that the phone stops receiving notifications for the account.

A tapped notification opens a page when its data includes a `url`, such as `/orders/42`. Only addresses on your app's own origin open, so a notification can't send the user to another website.

## Sending Notifications from Laravel

Store each phone's token against the user it belongs to. Then tell Laravel which devices belong to a user by implementing `Receives<Push>` on your user model:

```rust
impl Receives<Push> for User {
    fn route(&self) -> Option<Vec<Device>> {
        Some(self.devices.clone())
    }
}
```

Next, give a notification a `#[via(Push)]` method that returns a `PushMessage`. Its `url` is the page the phone opens when the user taps the notification, and `data` adds key and value pairs that your app can read:

```rust
#[notification]
impl ReceiptApproved {
    #[via(Push)]
    fn push(&self, _user: &User) -> PushMessage {
        PushMessage::new("Receipt approved")
            .body(format!("{} was approved.", self.merchant))
            .url(format!("/receipts/{}", self.id))
    }
}
```

Laravel skips a device when the app was uninstalled or its token was replaced, and the other devices still receive the notification. If one device's push is refused for another reason, the rest are still sent, and the send returns that error afterwards.

### Forgetting Uninstalled Phones

When Firebase or Apple says a device is gone, Laravel dispatches a `DeviceGone` event. Listen for it to delete the device, so you stop sending to it:

```rust
use laravel::event::{Event, listener};
use laravel_mobile::push::DeviceGone;

#[listener]
pub async fn forget_gone_device(event: Event<DeviceGone>) -> laravel::Result<()> {
    Device::query()
        .filter(Device::token.eq(&event.device.token))
        .delete()
        .await?;

    Ok(())
}
```

When a user logs out on a phone, delete that phone's device too, so it doesn't keep receiving their notifications. Have your logout form send the phone's token, and delete it before you log the user out.

## Configuring Credentials

Set the credentials in your `.env` file. Each one takes either a path, relative to your application, or the file's contents:

| Key | Purpose |
| --- | --- |
| `FIREBASE_CREDENTIALS` | The Firebase service account's JSON key, for Android. |
| `APNS_KEY` | The `.p8` key from Apple, for iOS. |
| `APNS_KEY_ID` | The ID of the `.p8` key. |
| `APNS_TEAM_ID` | Your Apple team ID. Defaults to `ios.team_id` in `mobile.toml`. |
| `APNS_TOPIC` | The bundle ID to send to. Defaults to `app.id` in `mobile.toml`. |
| `APNS_PRODUCTION` | Set to `true` for App Store and TestFlight builds. Development builds need it unset. |

If you would like to test your notifications without sending them, fake the HTTP client with `laravel::http::client::fake()`, as the package's own tests do.

## Next Steps

Read the [Native Plugins](https://docs.lairport.app/native-plugins/) guide to see the other features you can add to `mobile.toml`. The [JavaScript Adapter](https://docs.lairport.app/js-adapter/) guide describes `mobile.push` alongside the device APIs, and the [configuration](https://docs.lairport.app/configuration/#plugins) reference lists every plugin key.

Source: https://docs.lairport.app/push-notifications/index.mdx
