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);

// Create migration: php artisan make:migration create_notification_tokens_table
Schema::create('notification_tokens', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->string('token')->unique();
    $table->string('device_type')->nullable(); // 'android', 'ios', 'web'
    $table->timestamps();
});

// 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('Android Notification', 'Optimized for Android devices')
    ->setAndroidChannel('important_notifications')
    ->setAndroidPriority('high')
    ->setAndroidSound('custom_sound.mp3')
    ->addData('android_specific', 'value');

$user->notify($notification);

$message = FcmMessage::create('iOS Notification', 'Optimized for iOS devices')
    ->setIosBadge(5)                    // Badge count
    ->setIosSound('custom_sound.caf')   // Custom sound
    ->addData('ios_specific', 'value');

$user->notify($notification);

$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');
}

return [
    // Firebase Credentials (Required)
    'project_id' => env('FCM_PROJECT_ID'),
    'client_email' => env('FCM_CLIENT_EMAIL'),
    'private_key' => env('FCM_PRIVATE_KEY'),

    // API Settings
    'timeout' => env('FCM_TIMEOUT', 30), // Request timeout in seconds

    // Message Behavior
    'default_mode' => env('FCM_DEFAULT_MODE', 'data_only'), // 'notification_only', 'data_only', 'both'

    // Token Management
    'token_column' => env('FCM_TOKEN_COLUMN', 'token'),              // Column name for single token storage
    'auto_cleanup_tokens' => env('FCM_AUTO_CLEANUP_TOKENS', true),   // Auto-remove invalid tokens

    // Performance Settings
    'cache_token' => true,                              // Cache JWT tokens
    'cache_prefix' => 'fcm_notifications_token',        // Cache key prefix
];

// Debug token discovery
$user = User::find(1);
dd($user->notificationTokens); // For multiple tokens
dd($user->fcm_token);          // For single token

// Use queued notifications for better performance
class PushNotification extends FcmNotification implements ShouldQueue
{
    use Queueable;
}
bash
php artisan vendor:publish --tag=fcm-notifications-config
bash
php artisan make:notification PushNotification