Laravel notification showing "Registration token is not a valid FCM registration token" when integrating with FCM
P粉985686557
P粉985686557 2023-12-13 15:19:09
0
1
533

I have integrated FCM (Firebase Cloud Messaging) notifications with my Laravel project. I added method routeNotificationForFcm in User model. The notification system works fine when specifying the firebase device token directly in the method, but fails when accessing the token from the database.

The added working code is as follows.

public function routeNotificationForFcm()
{
    return ['dJQqgKlETpqCB3uxHtfUbL:APA91bFdrcXZMNH0iMjkXMoop_b_nI3xF92DU0P1nrHVQsTDK4w-OH5QR6BsnWIV-wSxSV7avzuBmLVizNyrRcKfAQz6H66JEP9rWKUeIi7m7wEZwRiuW_WdCW_LaZajdFZlxfCUonCL'];
}

The code that does not work is as follows (database query)

public function routeNotificationForFcm()
{
    return $this->from('fcm_tokens')->where('user_id', $user->id)->pluck('device_token');
}

The error message displayed is The registration token is not a valid FCM registration token

P粉985686557
P粉985686557

reply all(1)
P粉301523298

According to Laravel documentation pluck return Collection - so you only need to call after calling pluck on the query/collection toArray() returns an array, just like you did before with the mock token.

public function routeNotificationForFcm()
{
    return $this->from('fcm_tokens')->where('user_id', $user->id)->pluck('device_token')->toArray();
}

You also called $user->id, but not in this scope. The solution is simple, you need to pass the value or get the value from $this.

public function routeNotificationForFcm()
{
    return $this->from('fcm_tokens')->where('user_id', $this->id)->pluck('device_token')->toArray();
}

But I personally recommend that you define a separate relationship for this

public function fcmTokens()
{
    return $this->hasMany(FcmToken::class);
}

FcmToken - Just a guess on how you named your model. You can then reuse it like this to return an array of the relevant tokens for a specific User model

public function routeNotificationForFcm()
{
    return $this->fcmTokens()->pluck('device_token')->toArray();
}

Finally, if you structure your code like this, you will have a general relationship and use this relationship to make your code more flexible.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!