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']);
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
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.