Fcm for core already answered here How to send Notification to Android from php?
so in laravel you can
create a config file in config folder and name it as firebase.php
<?php
return [
'fcm_url'=>env('FCM_URL'),
'fcm_api_key'=>env('FCM_API_KEY'),
];
and in env file
FCM_URL=https://fcm.googleapis.com/fcm/send
FCM_API_KEY=
and in code you can create Trait class
<?php
namespace App\Traits;
use Illuminate\Support\Facades\Http;
trait Firebase
{
public function firebaseNotification($fcmNotification){
$fcmUrl =config('firebase.fcm_url');
$apiKey=config('firebase.fcm_api_key');
$http=Http::withHeaders([
'Authorization:key'=>$apiKey,
'Content-Type'=>'application/json'
]) ->post($fcmUrl,$fcmNotification);
return $http->json();
}
}
Then you can include this trait any class where you want to call
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use App\Traits\Firebase;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use Firebase,AuthenticatesUsers;
public function sendNotification(){
$token="";
$notification = [
'title' =>'title',
'body' => 'body of message.',
'icon' =>'myIcon',
'sound' => 'mySound'
];
$extraNotificationData = ["message" => $notification,"moredata" =>'dd'];
$fcmNotification = [
//'registration_ids' => $tokenList, //multple token array
'to' => $token, //single token
'notification' => $notification,
'data' => $extraNotificationData
];
return $this->firebaseNotification($fcmNotification);
}
}
Also i suggest to create events based to better code optimization
Also read
https://firebase.google.com/docs/cloud-messaging/http-server-ref
registration_ids for multiple users
This parameter specifies the recipient of a multicast message, a
message sent to more than one registration token.
The value should be an array of registration tokens to which to send
the multicast message. The array must contain at least 1 and at most
1000 registration tokens. To send a message to a single device, use
the to parameter.
Multicast messages are only allowed using the HTTP JSON format.
For new Version as mentioned in comment by @JEJ
https://firebase.google.com/docs/cloud-messaging/migrate-v1#python_1
So it will be
$http=Http::withHeaders([
'Authorization'=>'Bearer '.$apiKey,
'Content-Type'=>'application/json; UTF-8'
]) ->post($fcmUrl,$fcmNotification);
return $http->json();
and simple notification message for $fcmNotification
{
"message": {
"topic": "news",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"data": {
"story_id": "story_12345"
}
}
}
for targeting multiple platforms
{
"message": {
"topic": "news",
"notification": {
"title": "Breaking News",
"body": "New news story available."
},
"data": {
"story_id": "story_12345"
},
"android": {
"notification": {
"click_action": "TOP_STORY_ACTIVITY"
}
},
"apns": {
"payload": {
"aps": {
"category" : "NEW_MESSAGE_CATEGORY"
}
}
}
}
}