1. Go to this page and download the library: Download nylo/laravel-fcm-channel 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/ */
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Nylo\LaravelFCM\Traits\HasFcmDevices; // Use HasFcmDevices trait
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, HasFcmDevices; // Add it to your model
...
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return [
'mail',
'fcm_channel', // add this
];
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toFcm($notifiable)
{
return (new FcmMessage)
->title('Parcel Dispatched')
->body('Your parcel has been dispatched');
// or like this
return [
'title' => config('app.name'), // Title of the notification
'body' => $title, // Body of the notification
];
}
...
class User {
use HasFcmDevices;
/**
* Determines if the devices can be notified.
*
* @return bool
*/
public function canSendNotification($notification) : bool
{
// $notification - Will return the type of Notification you are trying to send.
// E.g. $user->notify(new NewsLetterNotification($order));
// $notification = 'App\Notifications\NewsLetterNotification';
//
// The canSendNotification method will be called before dispatching the fcm notification.
// If you return True, it will send. If you return False, it will not send.
if ($notification == 'App\Notifications\NewsLetterNotification') {
return ($this->receives_news_letters == true); // example condition
}
return true;
}
}
$notification = new FcmMessage();
$notification->title('My App'); // Title of the notification
$notification->body('Hello, World!'); // Body of the notification
$notification->image('https://example.com/image.jpg'); // Image URL
$notification->badge(1); // Badge number
$notification->sound('custom_sound'); // Sound to play (by default it will play the 'default' sound)
$notification->data(['key' => 'value']); // Custom data
$notification->withoutDefaultSound(); // Disable the default sound
$notification->priorityHighest(); // Set the priority to 'high'
$notification->priorityLowest(); // Set the priority to 'low'
$user = User::first();
$user->fcmDevices;// Returns all the FCM Devices that the user owns
// send notification
$fcmDevice = $user->fcmDevices->first();
$message = (new FcmMessage)
->title('My App')
->body('Hello, World!');
$fcmDevice->sendFcmMessage($message);
// or like this
$fcmDevice->sendFcmMessage([
'title' => 'My App',
'body' => 'Hello, World!'
]);