Sending Firebase push notifications from Laravel

11,761

After some research I have found a solution to my question. In order to work for iOS platform, we need to add notification in fields:

$notification = array('title' =>"" , 'text' => $request->all()['message']);
$fields = array(
    'to' => $tok,
    'data' => $message = array(
        "message" => $request->all()['message'],
        "dialog_id" => $dialog_id
    ),
    'notification' => $notification
);
Share:
11,761
Levan Karanadze
Author by

Levan Karanadze

iOS Developer

Updated on July 20, 2022

Comments

  • Levan Karanadze
    Levan Karanadze over 1 year

    I am writing an iOS application, using laravel for API and google firebase for push notifications. When I send a push notification using firebase cloud messaging, it comes to my device. When I send push notifications using laravel, it does not affect. Here is my script for sending push notifications from laravel:

    function sendNotification(Request $request)
    {
        $friendToken = [];
        $usernames = $request->all()['friend_usernames'];
        $dialog_id = $request->all()['dialog_id'];
        foreach ($usernames as $username) {
            $friendToken[] = DB::table('users')->where('user_name', $username)
                ->get()->pluck('device_token')[0];
        }
    
        $url = 'https://fcm.googleapis.com/fcm/send';
        foreach ($friendToken as $tok) {
            $fields = array(
                'to' => $tok,
                'data' => $message = array(
                    "message" => $request->all()['message'],
                    "dialog_id" => $dialog_id
                )
            );
            $headers = array(
                'Authorization: key=*mykey*',
                'Content-type: Application/json'
            );
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
            curl_exec($ch);
            curl_close($ch);
        }
    
        $res = ['error' => null, 'result' => "friends invited"];
    
        return $res;
    }
    

    It returns a successful result, but notification not sent to iOS devices.

    PS: It works successfully on Android devices.

  • Osuji Kingsley
    Osuji Kingsley about 4 years
    Just want to know how you send the received token to your database in laravel
  • Michael Yousrie
    Michael Yousrie about 4 years
    just a hint. you can use $request->only('message') to get the message from the request instead of $request->all()['message']. :)