iosswiftlaravelfirebasefirebase-cloud-messaging

Sending Firebase push notifications from Laravel


I work on the iOS application. I use Laravel (REST API) and Google Firebase (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.


Solution

  • 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
    );