search

Home  >  Q&A  >  body text

Laravel notification showing "Registration token is not a valid FCM registration token" when integrating with FCM

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粉985686557P粉985686557352 days ago559

reply all(1)I'll reply

  • P粉301523298

    P粉3015232982023-12-14 14:09:21

    According to Laravel documentation < code>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.

    reply
    0
  • Cancelreply