PHP code example of netosts / laravel-fcm-notifications
1. Go to this page and download the library: Download netosts/laravel-fcm-notifications library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
netosts / laravel-fcm-notifications example snippets
// Add to your users table migration
Schema::table('users', function (Blueprint $table) {
$table->string('fcm_token')->nullable();
});
// Make it fillable in your User model
class User extends Model
{
protected $fillable = ['fcm_token'];
}
use LaravelFcmNotifications\Notifications\FcmNotification;
$notification = new FcmNotification(
title: 'Welcome!',
body: 'Thanks for joining our app'
);
$user->notify($notification);
// Add to your users table migration
Schema::table('users', function (Blueprint $table) {
$table->string('fcm_token')->nullable();
});
class User extends Model
{
public function notificationTokens()
{
return $this->hasMany(NotificationToken::class);
}
}
// Optional: Create a NotificationToken model
class NotificationToken extends Model
{
protected $fillable = ['user_id', 'token', 'device_type'];
public function user()
{
return $this->belongsTo(User::class);
}
}
class User extends Model
{
protected $fillable = ['fcm_token'];
// Optional: Custom method name
public function getFcmToken()
{
return $this->fcm_token;
}
}
use LaravelFcmNotifications\Notifications\FcmNotification;
// Simple notification
$notification = new FcmNotification(
title: 'New Message',
body: 'You have a new message from John'
);
$user->notify($notification);
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use LaravelFcmNotifications\Notifications\FcmNotification;
class PushNotification extends FcmNotification implements ShouldQueue
{
use Queueable;
// Add custom logic here if needed
}
use App\Notifications\PushNotification;
$notification = new PushNotification(
title: 'New Message',
body: 'You have a new message from John',
image: 'https://example.com/avatar.jpg',
data: ['message_id' => '123', 'sender_id' => '456']
);
$user->notify($notification);
use LaravelFcmNotifications\Facades\Fcm;
use LaravelFcmNotifications\Services\FcmMessage;
// Create a detailed message
$message = FcmMessage::create(
title: 'Direct Message',
body: 'This message was sent directly via the service'
)
->addData('custom_key', 'custom_value')
->addData('user_action', 'view_profile')
->setAndroidPriority('high')
->setIosBadge(1);
// Send to a specific device
$result = Fcm::sendToDevice($deviceToken, $message);
// Handle the result
if ($result['success']) {
echo "Message sent successfully!";
} else {
echo "Failed to send: " . $result['error'];
}
$notification = new FcmNotification(
title: 'New Order',
body: 'You received a new order #1234',
data: ['order_id' => '1234', 'action' => 'view_order']
);
$notification = (new FcmNotification(
title: 'Background Sync', // Not shown to user
body: 'Data updated', // Not shown to user
data: ['sync' => 'true', 'timestamp' => time()]
))->dataOnly();
$notification = (new FcmNotification(
title: 'System Maintenance',
body: 'Our systems will be down for maintenance tonight'
))->notificationOnly();
$deviceTokens = ['token1', 'token2', 'token3'];
$message = FcmMessage::create(
title: 'System Announcement',
body: 'Important update for all users'
);
$result = Fcm::sendToMultipleDevices($deviceTokens, $message);
// Check results
echo "Successfully sent to: {$result['summary']['success']} devices\n";
echo "Failed to send to: {$result['summary']['failure']} devices\n";
// Handle individual failures
foreach ($result['details'] as $detail) {
if (!$detail['success']) {
echo "Failed for token: {$detail['token']}, Error: {$detail['error']}\n";
}
}
$message = FcmMessage::create('Universal Message', 'Works on all platforms')
// Android settings
->setAndroidPriority('high')
->setAndroidChannel('notifications')
// iOS settings
->setIosBadge(1)
->setIosSound('default')
// Common data
->addData('universal_data', 'value');
// In your EventServiceProvider
protected $listen = [
\LaravelFcmNotifications\Events\UnregisteredFcmTokenDetected::class => [
\LaravelFcmNotifications\Listeners\CleanupUnregisteredFcmToken::class,
],
];
use LaravelFcmNotifications\Facades\Fcm;
// Validate a single token
$validation = Fcm::validateToken($deviceToken);
if ($validation['valid']) {
echo "Token is valid and ready to receive notifications";
} else {
echo "Token is invalid: " . $validation['message'];
// Error type: $validation['error_type']
}
// Validate multiple tokens at once
$tokens = ['token1', 'token2', 'token3'];
$results = Fcm::validateTokens($tokens);
$validCount = 0;
$invalidCount = 0;
foreach ($results as $result) {
if ($result['valid']) {
$validCount++;
} else {
$invalidCount++;
// Remove invalid token from database
NotificationToken::where('token', $result['token'])->delete();
}
}
echo "Valid tokens: {$validCount}\n";
echo "Invalid tokens: {$invalidCount}\n";
// Only send notifications in production
if (app()->environment('production')) {
$user->notify(new PushNotification('Production Alert', 'This is live!'));
} else {
// Log instead of sending during development
Log::info('Would send notification: Production Alert');
}