First create a new laravel project and add this var to .env file in your project
FCM_SERVER_KEY=FIRE_BASE_SERVER_KEY
create a new controller NotificationController
public function send_message(Request $request)
{
// Call Your FCM Service Class
}
now create a new service in laravel at app/Services/FCMService.php
create a new function :
<?php
namespace App\Services;
use App\Models\User;
class FCMService
{
// send notification to user using firebase cloud messaging
public static function send_notification($user, $title, $body)
{
$user = User::where('id', $user)->first();
$url = "https://fcm.googleapis.com/fcm/send";
$server_key = env('FCM_SERVER_KEY');
$headers = [
'Authorization' => 'key=' . $server_key,
'Content-Type' => 'application/json',
];
if (!$user) {
return response()->json([
'status' => 'error',
'message' => 'User not found',
], 404);
}
// send via GuzzleHttp
$client = new \GuzzleHttp\Client();
$response = $client->post($url, [
'headers' => $headers,
'json' => [
'to' => $user->device_token, // user's device token for fcm
'data' => [
'title' => $title,
'body' => $body,
],
],
]);
return $response->getBody();
}
}
add new column to users table called device_token
store any new device token when user create a new account from mobile and use it to send notifications to user device from users table.
Now we can send request to the FCMService
public function send_message(Request $request)
{
// Call Your FCM Service Class
\App\Services\FCMService::send_notification($request->user_id, $request->title, $request->body);
return redirect()->back();
}
Top comments (0)