PHP code example of humamkerdiah / fcm-notifications

1. Go to this page and download the library: Download humamkerdiah/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/ */

    

humamkerdiah / fcm-notifications example snippets


use Humamkerdiah\FcmNotifications\Channels\FcmChannel;

class NewMessage extends Notification
{
    public function via($notifiable)
    {
        return [FcmChannel::class];
    }

    public function toFcm($notifiable)
    {
        return (new FcmMessage())
            ->setTitle('New Message')
            ->setBody('You have a new message!')
            ->setData([
                'message_id' => '123',
                'url' => '/messages/123'
            ]);
    }
}

class NewMessage extends Notification
{
    public function via($notifiable)
    {
        return ['fcm'];  // Use the registered channel name
    }

    public function toFcm($notifiable)
    {
        return (new FcmMessage())
            // ... same as above
    }
}

use Illuminate\Notifications\Notifiable;

class User extends Model
{
    use Notifiable;

    public function routeNotificationForFcm($notification)
    {
        return $this->device_token; // Return a single token
        // Or return multiple tokens:
        // return $this->device_tokens->pluck('token')->toArray();
    }
}

// To a single user
$user->notify(new NewMessage());

// To multiple users
Notification::send($users, new NewMessage());

// Using the facade for direct FCM operations
use Humamkerdiah\FcmNotifications\Facades\FcmNotification;

// Send to specific devices
$message = new FcmMessage();
$message->setTitle('Hello')
       ->setBody('This is a test notification')
       ->setData(['key' => 'value'])
       ->setTokens(['device-token-1', 'device-token-2']);

FcmNotification::sendToDevices($message);

// Or send to a topic
$message->setTopic('news');
FcmNotification::sendToTopic($message);

// Subscribe tokens to a topic
FcmNotification::subscribeToTopic('news', ['device-token-1', 'device-token-2']);

// Unsubscribe tokens from a topic
FcmNotification::unsubscribeFromTopic('news', ['device-token-1', 'device-token-2']);

try {
    $result = FcmNotification::sendToDevices($message);
    
    echo "Success count: " . $result['success_count'];
    echo "Failure count: " . $result['failure_count'];
    
    // Handle successful sends
    foreach ($result['results'] as $result) {
        echo "Token: " . $result['token'] . " - Message ID: " . $result['message_id'];
    }
    
    // Handle failures
    foreach ($result['errors'] as $error) {
        echo "Failed token: " . $error['token'] . " - Error: " . $error['error'];
    }
    
} catch (\Humamkerdiah\FcmNotifications\Exceptions\FcmNotificationException $e) {
    Log::error('FCM Notification failed: ' . $e->getMessage());
}

try {
    $result = FcmNotification::sendToDevices($message);
    
    echo "Success: " . $result['success'];
    echo "Failure: " . $result['failure'];
    echo "Canonical IDs: " . $result['canonical_ids'];
    
} catch (\Exception $e) {
    Log::error('FCM Notification failed: ' . $e->getMessage());
}

use Mockery;
use Humamkerdiah\FcmNotifications\Contracts\FcmNotificationSender;

public function test_it_sends_fcm_notification()
{
    $mock = Mockery::mock(FcmNotificationSender::class);
    
    // For v1 API
    $mock->shouldReceive('sendToDevices')->once()->andReturn([
        'success_count' => 1,
        'failure_count' => 0,
        'results' => [['token' => 'test-token', 'success' => true, 'message_id' => 'test-message-id']],
        'errors' => []
    ]);
    
    $this->app->instance(FcmNotificationSender::class, $mock);

    // Your test code here
}
bash
php artisan vendor:publish --tag=fcm-config