The Vibes — the unofficial Laracon US Day 3 event. Early Bird tickets available until March 31!
Blog

🔔 Push Notifications: The Complete Setup Guide

Your app is installed. Your user closes it. How do you bring them back?

Push notifications are the lifeblood of user engagement. NativePHP makes them simple — one API handles both iOS (APNs) and Android (FCM).

In this post:

#How It Works

  1. User enrolls — Your app requests permission and gets a device token
  2. You store the token — Save it to your backend
  3. You send notifications — Push from your server
  4. User receives it — Even when the app is closed

#Request Permission

#PHP (Livewire)

Copied!
use Native\Mobile\Facades\PushNotifications;
use Native\Mobile\Events\PushNotification\TokenGenerated;
 
public function enableNotifications()
{
PushNotifications::enroll();
}
 
#[On('native:' . TokenGenerated::class)]
public function handleToken(string $token)
{
auth()->user()->update(['push_token' => $token]);
$this->enrolled = true;
}

#JavaScript (Vue/React/Inertia)

Copied!
import { PushNotifications, On, Off, Events } from '@nativephp/mobile';
 
const enableNotifications = async () => {
await PushNotifications.enroll();
};
 
On(Events.PushNotification.TokenGenerated, ({ token }) => {
// Send token to your backend
fetch('/api/push-token', {
method: 'POST',
body: JSON.stringify({ token })
});
enrolled.value = true;
});

#Handle the Token

#Check Current Token (PHP)

Copied!
$token = PushNotifications::getToken();
 
if ($token) {
// User has notifications enabled
}

#Check Current Token (JavaScript)

Copied!
import { PushNotifications } from '@nativephp/mobile';
 
const token = await PushNotifications.getToken();
 
if (token) {
// User has notifications enabled
}

#Send from Your Backend

Copied!
class PushService
{
public function send(string $token, string $title, string $body): bool
{
return Http::withHeaders([
'Authorization' => 'key=' . config('services.fcm.key'),
])->post('https://fcm.googleapis.com/fcm/send', [
'to' => $token,
'notification' => compact('title', 'body'),
])->successful();
}
}

#Best Practices

  1. Ask at the right time — Not on first launch
  2. Explain the value — Tell users what they'll get
  3. Don't spam — Every unnecessary notification erodes trust
  4. Handle token refresh — Tokens can change

#Token Refresh (PHP)

Copied!
#[On('native:' . TokenGenerated::class)]
public function handleToken(string $token)
{
$user = auth()->user();
if ($user->push_token !== $token) {
$user->update(['push_token' => $token]);
}
}

#Token Refresh (JavaScript)

Copied!
On(Events.PushNotification.TokenGenerated, ({ token }) => {
if (currentToken.value !== token) {
updateToken(token);
}
});

You've got push notifications. Use them wisely, and your users will thank you by coming back.

Happy pinging! 🔔