Skip to content
Puneetpal Arneja.Start a project
By • Published • Updated

Push Notifications from Laravel to iOS and Android (APNs + FCM)

A Laravel API sends push notifications by talking to two services: Apple Push Notification service for iOS and Firebase Cloud Messaging for Android. Each has its own authentication, its own payload rules, and its own way of telling you a device is gone. The code is not long. Most of the work is in storing tokens correctly, sending from a queue, and acting on the error responses so the queue does not fill with devices that no longer exist.

This article is one part of a larger guide to Laravel as a backend for mobile apps, which covers the authentication, versioning, and sync decisions that push depends on. Here I go through the parts the hub only summarises, from credentials to testing, as a sequence you can follow top to bottom. The PHP targets Laravel 12 and 13 with laravel-notification-channels/apn 6.x (PHP 8.4) and laravel-notification-channels/fcm 6.x (PHP 8.3); the Swift targets iOS 17 and later.

How the Two Services Authenticate You

APNs token-based authentication uses a .p8 private key you download once from the Apple Developer account under Keys. Your server signs a JWT with it: the header carries alg: ES256 and kid, the 10-character key ID; the claims carry iss, your 10-character team ID, and iat, the issue time. The JWT goes in an authorization: bearer header on every request. APNs rejects a token whose iat is more than an hour old with 403 ExpiredProviderToken, and it rejects you for refreshing more often than every 20 minutes with 429 TooManyProviderTokenUpdates, so cache the signed JWT and regenerate it on a schedule between those two limits. The client libraries below do this for you; it matters when you roll your own.

A team-scoped key signs for every app on the team, which is why the hub article tells you to prefer it over a per-app certificate: it does not expire, and one secret covers all your bundle IDs. Each request names the app through the apns-topic header, which for an alert or background push is the bundle ID exactly. The production host is api.push.apple.com and the sandbox host is api.sandbox.push.apple.com, both on port 443 (2197 also works), both HTTP/2 only. A device token belongs to one environment. Debug builds signed with the development aps-environment entitlement produce sandbox tokens; TestFlight and App Store builds produce production tokens. Mixing them earns a 400 BadDeviceToken.

FCM HTTP v1 authenticates with a Google service account. You generate a JSON key in the Firebase console under Project settings, Service accounts, and your server exchanges it for a short-lived OAuth2 access token with the scope https://www.googleapis.com/auth/firebase.messaging. Requests go to https://fcm.googleapis.com/v1/projects/PROJECT_ID/messages:send with Authorization: Bearer. The older legacy HTTP API that took a static server key was deprecated in 2023 and shut down in 2024. Any tutorial or package that posts to fcm.googleapis.com/fcm/send with a key= header no longer works, and a lot of Laravel material still does.

Both secrets are server-only. The .p8 contents and the service account JSON go in environment variables or a secrets manager, never in the repository and never anywhere the mobile app can reach.

Step 1: Create the Credentials

Apple first. You need three values and one file.

  1. In the Apple Developer account open Certificates, Identifiers & Profiles, then Keys, and click the plus button. Name the key, tick Apple Push Notifications service (APNs), click Continue, then Register.
  2. Click Download. This is the only time Apple will give you the .p8 file; if you lose it you revoke the key and make another. Note the Key ID shown on the same page.
  3. Note your Team ID from Membership details. Note the bundle ID of the app from the Identifiers list or from the Xcode target.
  4. In the Xcode target, under Signing & Capabilities, add the Push Notifications capability. If you will send background pushes, also add Background Modes and tick Remote notifications. Debug builds now carry aps-environment: development; distribution builds carry production.

Then Firebase, for Android.

  1. In the Firebase console open Project settings, then Service accounts, and click Generate new private key. Save the JSON somewhere the PHP worker can read, outside the web root, for example storage/app/private/firebase.json, and add that path to .gitignore.
  2. Confirm the Android app registers with the same Firebase project: the google-services.json in the Android project must carry the same project_id as the service account JSON. A mismatch surfaces later as SENDER_ID_MISMATCH.

Step 2: Install and Configure the Packages

Laravel’s notification system already has the shape you need: a notification class, a via() method that picks channels, a toX() method per channel, and routing methods on the notifiable model. Two packages from the laravel-notification-channels organisation supply the channels.

  • laravel-notification-channels/apn wraps edamov/pushok, an HTTP/2 APNs client that handles the JWT. Version 6 requires PHP 8.4 and ext-curl built with HTTP/2 support, which most PHP images have but some older shared hosts do not.
  • laravel-notification-channels/fcm wraps kreait/laravel-firebase, which handles the service account and the OAuth2 token. Version 6 requires PHP 8.3 and reads FIREBASE_CREDENTIALS from the environment.
  1. Check HTTP/2 support before installing anything: php -r 'var_dump((bool) (curl_version()["features"] & CURL_VERSION_HTTP2));' must print bool(true). If it prints false, APNs sends will fail with a connection error and no amount of configuration fixes it; change the PHP image.
  2. Install: composer require laravel-notification-channels/apn laravel-notification-channels/fcm.
  3. Add the APN connection to config/broadcasting.php. The key content goes in the environment variable with literal \n line breaks inside double quotes, which Laravel’s env parser turns back into newlines.
<?php
// config/broadcasting.php
return [
    // ...
    'connections' => [
        // ...
        'apn' => [
            'key_id' => env('APN_KEY_ID'),
            'team_id' => env('APN_TEAM_ID'),
            'app_bundle_id' => env('APN_BUNDLE_ID'),
            'private_key_content' => env('APN_PRIVATE_KEY'),
            'production' => env('APN_PRODUCTION', true),
        ],
    ],
];
# .env
APN_KEY_ID=ABC123DEFG
APN_TEAM_ID=TEAM123456
APN_BUNDLE_ID=com.example.shop
APN_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQg...\n-----END PRIVATE KEY-----"
APN_PRODUCTION=false

FIREBASE_CREDENTIALS=/var/www/app/storage/app/private/firebase.json
  1. Set APN_PRODUCTION=false on local and staging so sandbox tokens from debug builds reach the sandbox host, and true in production.
  2. Verify the config loads: php artisan tinker, then config('broadcasting.connections.apn.key_id') should print your key ID and str_contains(config('broadcasting.connections.apn.private_key_content'), "\n") should be true. If the second is false, the quotes around the key in .env are missing or single.
  3. Verify Firebase can read its credentials: in tinker, run Kreait\Laravel\Firebase\Facades\Firebase::messaging(). It throws if the JSON path is wrong or unreadable by the current user, and returns a Messaging instance if not.

Step 3: Store Device Tokens

A user has many devices, and a device token is per app per device. A single push_token column on users breaks the moment someone signs in on a tablet. Store one row per token with enough context to debug a delivery problem later: platform, app version, and when the device last checked in.

<?php
// database/migrations/2026_01_01_000000_create_device_tokens_table.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::create('device_tokens', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->string('platform', 10);           // ios | android
            $table->string('token', 512)->unique();   // APNs hex token or FCM registration token
            $table->string('app_version', 20);
            $table->string('device_name', 100)->nullable();
            $table->string('locale', 10)->nullable();
            $table->timestamp('last_seen_at');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('device_tokens');
    }
};
<?php
// app/Models/DeviceToken.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DeviceToken extends Model
{
    protected $fillable = ['user_id', 'platform', 'token', 'app_version', 'device_name', 'locale', 'last_seen_at'];

    protected function casts(): array
    {
        return ['last_seen_at' => 'datetime'];
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}
<?php
// routes/api.php

use App\Models\DeviceToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->put('/devices', function (Request $request) {
    $data = $request->validate([
        'platform' => ['required', 'in:ios,android'],
        'token' => ['required', 'string', 'max:512'],
        'app_version' => ['required', 'string', 'max:20'],
        'device_name' => ['nullable', 'string', 'max:100'],
        'locale' => ['nullable', 'string', 'max:10'],
    ]);

    DeviceToken::updateOrCreate(
        ['token' => $data['token']],
        [...$data, 'user_id' => $request->user()->id, 'last_seen_at' => now()]
    );

    return response()->noContent();
});

Route::middleware('auth:sanctum')->delete('/devices/{token}', function (Request $request, string $token) {
    $request->user()->deviceTokens()->where('token', $token)->delete();

    return response()->noContent();
});

The upsert is keyed on the token, not the user. If a second person signs in on the same phone, the row moves to them, so the previous owner stops receiving pushes on a phone they no longer hold. The app calls the delete endpoint on logout with the token it holds, and a password reset can delete all of a user’s rows.

The app calls the upsert on every launch. Apple’s documentation on registering with APNs is explicit: call registerForRemoteNotifications() each time, forward whatever token arrives in didRegisterForRemoteNotificationsWithDeviceToken, and never cache it locally, because the token changes after a restore from backup or a reinstall. The same holds for FCM registration tokens. Registration does not need the user’s notification permission; ask for that separately, at the point in your flow where the user understands why.

// AppDelegate.swift
import UIKit

final class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        application.registerForRemoteNotifications()   // every launch; the token can change
        return true
    }

    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let token = deviceToken.map { String(format: "%02x", $0) }.joined()
        Task { try? await api.registerDevice(token: token, platform: "ios") }   // PUT /api/devices
    }

    func application(_ application: UIApplication,
                     didFailToRegisterForRemoteNotificationsWithError error: Error) {
        // The Simulator and devices with no network path land here. Log it; do not retry in a loop.
    }
}

api is your API client; the call it makes is the PUT /api/devices above with the Sanctum bearer token. Which user the row belongs to comes from that token, so this endpoint sits behind the same guard as everything else. If you have not settled that layer yet, the Sanctum vs Passport comparison covers per-device API tokens, which pair naturally with per-device push tokens.

Verify: run the debug build on a physical device (the Simulator never receives an APNs token), log in, and check select platform, left(token, 12), app_version from device_tokens;. One row per device you have signed in on, and the row moves between users when you switch accounts.

Step 4: Send Through Laravel Notifications

The notification decides which channels to use from the tokens the user actually has, so a user with only an Android phone never triggers an empty APNs send.

<?php
// app/Notifications/OrderShipped.php

namespace App\Notifications;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use NotificationChannels\Apn\ApnChannel;
use NotificationChannels\Apn\ApnMessage;
use NotificationChannels\Fcm\FcmChannel;
use NotificationChannels\Fcm\FcmMessage;
use NotificationChannels\Fcm\Resources\Notification as FcmNotification;

class OrderShipped extends Notification implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;
    public array $backoff = [30, 120, 600];

    public function __construct(public Order $order)
    {
        $this->onQueue('push');
    }

    public function via(object $notifiable): array
    {
        $platforms = $notifiable->deviceTokens()->pluck('platform')->unique()->all();

        return collect([
            'ios' => ApnChannel::class,
            'android' => FcmChannel::class,
        ])->only($platforms)->values()->all();
    }

    public function toApn(object $notifiable): ApnMessage
    {
        return ApnMessage::create()
            ->title('Order shipped')
            ->body("Order #{$this->order->number} is on its way.")
            ->sound()
            ->threadId("order-{$this->order->id}")
            ->collapseId("order-{$this->order->id}")
            ->custom(['order_id' => $this->order->id]);
    }

    public function toFcm(object $notifiable): FcmMessage
    {
        return (new FcmMessage(notification: new FcmNotification(
            title: 'Order shipped',
            body: "Order #{$this->order->number} is on its way.",
        )))
            ->data(['order_id' => (string) $this->order->id])
            ->android([
                'collapse_key' => "order-{$this->order->id}",
                'notification' => ['channel_id' => 'orders'],
            ]);
    }
}
<?php
// app/Models/User.php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ...

    public function deviceTokens(): HasMany
    {
        return $this->hasMany(DeviceToken::class);
    }

    public function routeNotificationForApn(): array
    {
        return $this->deviceTokens()->where('platform', 'ios')->pluck('token')->all();
    }

    public function routeNotificationForFcm(): array
    {
        return $this->deviceTokens()->where('platform', 'android')->pluck('token')->all();
    }
}

Two details are easy to miss. FCM data values must be strings, so the order ID is cast; the package throws InvalidArgumentException for anything else before the request is even sent. And the APN channel sends all of a user’s tokens in one batch over HTTP/2 while the FCM channel chunks tokens into multicast calls of 500, so a single $user->notify() covers all of a user’s devices without a loop in your code.

Send one from tinker to a user whose device you hold: User::find(1)->notify(new App\Notifications\OrderShipped(Order::first()));. Nothing arrives yet, because the notification is queued; that is the next step.

Step 5: Run the Queue and Decide What to Retry

ShouldQueue on the notification class keeps the APNs round trip out of the HTTP request that triggered it. The dedicated push queue matters as much: run it on its own worker so a bulk announcement to every user cannot delay a password-reset code sitting behind it. A marketing send belongs on a third queue with fewer workers.

  1. Set QUEUE_CONNECTION=database or redis in .env; the default sync driver would send inside the web request and hide the problem this step exists to solve.
  2. Start a worker that owns the push queue: php artisan queue:work --queue=push --tries=3 --timeout=60. In production that line lives in a Supervisor program or a Horizon supervisor with queue: [push], separate from the default worker.
  3. Re-run the tinker send. The notification should arrive within a few seconds. If it does not, the troubleshooting list in Step 7 is in the order to check.

Retries need judgement, because the two services distinguish failures you should retry from failures you must not. Apple’s response documentation says retry 5xx with back-off, retry 429 TooManyRequests after a delay, and never retry BadDeviceToken, DeviceTokenNotForTopic, Unregistered, ExpiredToken, or PayloadTooLarge. APNs also slows your throughput after a stream of 4xx errors, so blind retries of a bad token hurt your good sends. FCM’s error codes follow the same split: retry UNAVAILABLE (503) honouring any Retry-After header and INTERNAL (500) with exponential back-off, back off at least a minute on QUOTA_EXCEEDED (429), and drop UNREGISTERED (404), INVALID_ARGUMENT (400), and SENDER_ID_MISMATCH (403), the last of which means the token was issued to a different Firebase project and will never work from yours.

The $tries and $backoff properties above handle the transient case: the channel packages throw on a connection failure or a 5xx, the job fails, and Laravel retries at 30 seconds, two minutes, and ten minutes before moving it to failed_jobs. The permanent case does not throw. Both packages report a per-token failure by dispatching Laravel’s NotificationFailed event and carry on, which is the hook for the next step.

Step 6: Prune Dead Tokens

Tokens die on uninstall, on restore to a new phone, and after long disuse. Neither service tells you proactively. You find out on the next send: APNs answers 410 Unregistered with a timestamp of when the token stopped being valid, and FCM answers 404 UNREGISTERED. A listener on NotificationFailed turns those into deletes. Laravel 11 and later discover the listener from the type hint on handle(), so there is nothing to register.

<?php
// app/Listeners/PruneDeadDeviceTokens.php

namespace App\Listeners;

use App\Models\DeviceToken;
use Illuminate\Notifications\Events\NotificationFailed;
use NotificationChannels\Apn\ApnChannel;
use NotificationChannels\Fcm\FcmChannel;

class PruneDeadDeviceTokens
{
    private const APNS_DEAD = ['Unregistered', 'ExpiredToken', 'BadDeviceToken', 'DeviceTokenNotForTopic'];

    public function handle(NotificationFailed $event): void
    {
        if ($event->channel === ApnChannel::class) {
            // The channel forwards pushok's parsed response: ['id' => ..., 'token' => ..., 'error' => reason]
            if (in_array($event->data['error'] ?? null, self::APNS_DEAD, true)) {
                DeviceToken::where('token', $event->data['token'])->delete();
            }

            return;
        }

        if ($event->channel === FcmChannel::class) {
            // The channel forwards one Kreait\Firebase\Messaging\SendReport per failed token
            $report = $event->data['report'];

            if ($report->messageWasSentToUnknownToken() || $report->messageTargetWasInvalid()) {
                DeviceToken::where('token', $report->target()->value())->delete();
            }
        }
    }
}

Apple adds one refinement: keep the token if the device registered again after the 410 timestamp. The APN channel does not forward the timestamp, so you either accept an occasional unnecessary delete (the app re-registers on next launch, so the cost is one missed push) or call pushok directly and read get410Timestamp(). I take the first option unless a missed push is a support ticket.

Pruning on errors is reactive. Pair it with a scheduled job that deletes rows whose last_seen_at is older than a few months. Those devices have not opened the app in that time, the push is unlikely to be welcome, and it keeps the table from growing with every reinstall.

<?php
// routes/console.php

use App\Models\DeviceToken;
use Illuminate\Support\Facades\Schedule;

Schedule::call(function () {
    DeviceToken::where('last_seen_at', '<', now()->subMonths(6))->delete();
})->daily()->name('prune-stale-device-tokens');

Verify the listener by deleting the app from your test device, sending once more, and checking that the row is gone after the worker processes the job. php artisan event:list should show PruneDeadDeviceTokens under NotificationFailed; if it does not, the file is outside app/Listeners or the event cache is stale (php artisan event:clear).

Payload Rules Worth Knowing

  • The limit is 4,096 bytes on both services. APNs allows 5,120 for VoIP pushes only. Over the limit means 413 PayloadTooLarge from APNs or INVALID_ARGUMENT from FCM, and neither is retryable.
  • On APNs, system keys (alert, badge, sound, thread-id, category, content-available, mutable-content, interruption-level) live inside the aps dictionary and your own keys live outside it. ApnMessage::custom() places them correctly.
  • apns-collapse-id (64 bytes max) and FCM’s Android collapse_key replace an earlier undelivered notification with the same ID, so a user who was offline sees one “order shipped” rather than five status updates.
  • apns-expiration is a UNIX timestamp after which APNs stops trying. Zero means one attempt and discard. Set it short for time-sensitive content like a verification code, which is useless an hour later; ApnMessage::expiresAt() takes a DateTime. The FCM equivalent is ttl in the android block.
  • Send identifiers, not content. The lock screen is readable by anyone holding the phone, the payload travels through two third parties, and the app can fetch the full record over the authenticated API once opened. A title, a short body, and an order_id is usually the whole payload.

Silent and Background Pushes

A background push wakes the app without showing anything, so it can refresh data before the user opens it. On APNs the rules are strict, and Apple’s documentation lists them: the aps dictionary contains only content-available: 1, the headers are apns-push-type: background and apns-priority: 5 (priority 10 is an error for this type), and the app gets 30 seconds in application(_:didReceiveRemoteNotification:fetchCompletionHandler:) to do its work and call the handler.

The limits are what make background pushes a poor delivery mechanism. Apple asks for no more than two or three per hour per device and throttles beyond that. Delivery is not guaranteed. The system holds only the newest one, so a burst collapses to a single wake. And if the user force-quit the app, the push is discarded and nothing runs until they open it again. On Android, the equivalent is a data-only FCM message; a normal priority message waits for the next Doze maintenance window, and high priority is meant for messages the user will see immediately, with Google throttling apps that use it for background work.

Use a background push as a hint that something changed, and make the app’s own sync on foreground the source of truth. With the APN package the message is built without title(), body(), or sound():

<?php
// app/Notifications/OrdersChanged.php (toApn only; via() and the class header as in OrderShipped)

namespace App\Notifications;

use Illuminate\Notifications\Notification;
use NotificationChannels\Apn\ApnMessage;
use NotificationChannels\Apn\ApnMessagePriority;
use NotificationChannels\Apn\ApnMessagePushType;

class OrdersChanged extends Notification
{
    public function toApn(object $notifiable): ApnMessage
    {
        return ApnMessage::create()
            ->contentAvailable()
            ->pushType(ApnMessagePushType::Background)
            ->priority(ApnMessagePriority::Low)
            ->custom(['changed' => 'orders']);
    }
}

Rich Media with a Notification Service Extension

An image in the notification does not fit in 4 KB, so iOS lets a small extension run before display and download it. The payload needs mutable-content: 1 inside aps and must include an alert; a badge-only or sound-only push never reaches the extension. From ApnMessage that is ->mutableContent()->custom(['image_url' => $url]). On the app side, add a Notification Service Extension target in Xcode (File, New, Target, Notification Service Extension) and replace the generated class with this one.

import UserNotifications

final class NotificationService: UNNotificationServiceExtension {
    private var contentHandler: ((UNNotificationContent) -> Void)?
    private var bestAttempt: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest,
                             withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttempt = request.content.mutableCopy() as? UNMutableNotificationContent

        guard let bestAttempt,
              let urlString = request.content.userInfo["image_url"] as? String,
              let url = URL(string: urlString) else {
            contentHandler(request.content)
            return
        }

        Task {
            if let downloaded = try? await URLSession.shared.download(from: url) {
                let file = downloaded.0.deletingPathExtension().appendingPathExtension("jpg")
                try? FileManager.default.moveItem(at: downloaded.0, to: file)
                if let attachment = try? UNNotificationAttachment(identifier: "image", url: file) {
                    bestAttempt.attachments = [attachment]
                }
            }
            contentHandler(bestAttempt)
        }
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler, let bestAttempt {
            contentHandler(bestAttempt)
        }
    }
}

The extension has about 30 seconds. If the download has not finished, the system calls serviceExtensionTimeWillExpire() and you hand back whatever you have; if you call neither handler, the original payload is shown. Keep images small and served from a CDN, because the extension runs on cellular as often as Wi-Fi. The attachment file must have a recognised extension, which is why the temporary download is renamed before it is attached.

Step 7: Test, and What to Check When Nothing Arrives

The iOS Simulator cannot register with APNs, but since Xcode 11.4 it accepts a payload directly. Write the JSON to a file with a .apns extension, add a top-level Simulator Target Bundle key so you do not have to pass the bundle ID, and push it to the booted device. The file is the exact payload the server would send, which makes it a good fixture for the app side of the work before the backend exists.

// order-shipped.apns
{
  "Simulator Target Bundle": "com.example.shop",
  "aps": {
    "alert": { "title": "Order shipped", "body": "Order #1042 is on its way." },
    "sound": "default",
    "thread-id": "order-1042",
    "mutable-content": 1
  },
  "order_id": 1042,
  "image_url": "https://cdn.example.com/orders/1042.jpg"
}

$ xcrun simctl push booted order-shipped.apns

Real devices need the full path. A test endpoint on staging that sends a fixed notification to the caller’s own devices exercises the credentials, the queue, the worker, and the pruning listener together. Gate it on environment and rate limit it; it should not exist in production.

<?php
// routes/api.php

use App\Notifications\TestPush;   // same shape as OrderShipped, with fixed copy and no model
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth:sanctum', 'throttle:5,1'])->post('/devices/test-push', function (Request $request) {
    abort_unless(app()->environment(['local', 'staging']), 404);

    $request->user()->notify(new TestPush());

    return response()->noContent();
});

When a push from staging does not arrive, check in this order. Each line is a symptom and its fix.

  1. Nothing in the logs and nothing in failed_jobs: no worker is consuming the push queue. Run php artisan queue:work --queue=push in a terminal and watch the job appear.
  2. 403 InvalidProviderToken from APNs: the Key ID, Team ID, or key content do not belong together, or the key was revoked. Re-check the three values against the Keys page.
  3. 400 BadDeviceToken: environment mismatch. A debug build needs APN_PRODUCTION=false; a TestFlight build needs true.
  4. 400 DeviceTokenNotForTopic, BadTopic, or MissingTopic: the bundle ID in APN_BUNDLE_ID is not the bundle ID of the build that registered the token.
  5. 403 SENDER_ID_MISMATCH from FCM: the Android app and the service account belong to different Firebase projects. Compare project_id in both JSON files.
  6. An authentication error from the Kreait client: FIREBASE_CREDENTIALS points at a file the worker’s user cannot read, or at the wrong path on the server. The path that works in your shell may not be the path the Supervisor-managed worker sees.
  7. APNs returned 200 and nothing appeared: the device has notifications turned off for the app, or the payload has no alert. Log the apns-unique-id response header; Apple’s Push Notifications Console in the developer account looks it up and shows what happened to the notification after it left your server.
  8. It arrived once and never again: the token changed and the app did not re-register. Confirm registerForRemoteNotifications() runs on every launch, not only on first install.

When Not to Push

Push is for things the user wants to know about while the app is closed. For data that should be fresh while the app is open, use a WebSocket through Laravel broadcasting or polling on a timer; both are more reliable than background pushes and have no hourly budget. For events that do not merit an interruption, write them to an in-app inbox the app fetches on launch. Once a user turns notifications off in Settings, no server-side change gets them back.

Sources

Where This Fits

Push is the last piece most mobile backends add and the first one users notice when it goes wrong. The device token endpoint sits behind the auth layer, the notification jobs sit on the queue, and the payload rules overlap with the data-exposure items in the Laravel API security checklist. If you would rather have the whole backend built with push, auth, and sync designed together, see backend API development.

Frequently Asked Questions

Do I need Firebase to send push notifications to iOS from Laravel?

No. iOS devices receive pushes from APNs, and Laravel can talk to APNs directly over HTTP/2 using a .p8 signing key. FCM can relay to APNs for you, which keeps one send path for both platforms, but it adds a hop, requires an APNs key uploaded to Firebase, and hides APNs error reasons behind FCM's. Talking to APNs directly is the simpler option when the backend already handles the two platforms separately.

How should Laravel store push notification device tokens?

One row per device, not one column on the user. Store the token (unique), the user it belongs to, the platform, the app version, and a last-seen timestamp. The app re-registers on every launch through an upsert endpoint, because APNs and FCM can issue a new token at any time and the app is the only party that knows. Delete the row on logout and when the push service reports the token as unregistered.

Why does APNs return 400 BadDeviceToken from my Laravel server?

Usually an environment mismatch. A debug build signed with the development aps-environment entitlement registers a sandbox token, which is only valid on api.sandbox.push.apple.com. TestFlight and App Store builds register production tokens for api.push.apple.com. Sending a sandbox token to the production host, or the other way round, fails with BadDeviceToken. Keep the production flag in config per environment and do not retry these.

What is the maximum size of a push notification payload?

4,096 bytes on both services. APNs allows 4 KB for regular notifications and 5 KB for VoIP pushes, and rejects larger payloads with 413 PayloadTooLarge. FCM allows 4,096 bytes for both notification and data messages, with a lower limit when sending from the Firebase console. In practice a payload should carry a title, a body, and an identifier; the app fetches the rest over the authenticated API.

How often can I send silent background pushes to an iOS app?

Apple's guidance is no more than two or three per hour per device. Background pushes use apns-push-type background and apns-priority 5, carry only content-available 1 in the aps dictionary, are not guaranteed to arrive, and are discarded if the user has force-quit the app. The system also holds only the most recent one. They suit a hint to refresh, not a delivery channel.

Puneetpal Arneja, Senior iOS, Web & Software Developer

Written by

Senior iOS, Web & Software Developer · 13+ years building apps and software

I've shipped 18+ mobile applications across banking, healthcare, and consumer products — including work for Citibank, Apple, PNC, and Albertsons. Everything here comes out of production work, not theory.

Need Push Built into Your Backend?

I build Laravel APIs for iOS, Android, and Flutter apps, including APNs and FCM delivery, device token lifecycles, and the queue and pruning work that keeps notifications arriving.

Related Services & Further Reading