PushNotifications
#Overview
The PushNotifications API handles device registration for Firebase Cloud Messaging to receive push notifications.
Import
Copied!
use Native\Mobile\Facades\PushNotifications;
Copied!
import { pushNotifications, on, off, Events } from '#nativephp';
#Methods
#enroll()
Requests permission and enrolls the device for push notifications.
Returns: void
Enroll for Push Notifications
Copied!
PushNotifications::enroll();
Copied!
// Basic enrollmentawait pushNotifications.enroll(); // With identifier for trackingawait pushNotifications.enroll() .id('main-enrollment') .remember();
#getToken()
Retrieves the current push notification token for this device.
Returns: string|null - The FCM token, or null if not available
Get Push Token
Copied!
$token = PushNotifications::getToken();
Copied!
const result = await pushNotifications.getToken();const token = result.token; // APNS token on iOS, FCM token on Android
#Events
#TokenGenerated
Fired when a push notification token is successfully generated.
Payload: string $token - The FCM token for this device
TokenGenerated Event
Copied!
use Native\Mobile\Attributes\OnNative;use Native\Mobile\Events\PushNotification\TokenGenerated; #[OnNative(TokenGenerated::class)]public function handlePushToken(string $token){ // Send token to your backend $this->sendTokenToServer($token);}
Copied!
import { on, off, Events } from '#nativephp';import { onMounted, onUnmounted } from 'vue'; const handleTokenGenerated = (payload) => { const { token } = payload; // Send token to your backend sendTokenToServer(token);}; onMounted(() => { on(Events.PushNotification.TokenGenerated, handleTokenGenerated);}); onUnmounted(() => { off(Events.PushNotification.TokenGenerated, handleTokenGenerated);});
Copied!
import { on, off, Events } from '#nativephp';import { useEffect } from 'react'; const handleTokenGenerated = (payload) => { const { token } = payload; // Send token to your backend sendTokenToServer(token);}; useEffect(() => { on(Events.PushNotification.TokenGenerated, handleTokenGenerated); return () => { off(Events.PushNotification.TokenGenerated, handleTokenGenerated); };}, []);
#Permission Flow
- User taps "Enable Notifications"
- App calls
enroll() - System shows permission dialog
- If granted, FCM generates token
TokenGeneratedevent fires with token- App sends token to backend
- Backend stores token for user
- Server can now send notifications to this device
#Best Practices
- Request permission at the right time (not immediately on app launch)
- Explain the value of notifications to users
- Handle permission denial gracefully