I have integrated FCM (Firebase Cloud Messaging) notifications with my Laravel project. I added methodrouteNotificationForFcminUsermodel. 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 isThe registration token is not a valid FCM registration token
According toLaravel documentationpluck return
Collection- so you only need to callafter callingpluckon the query/collection toArray()returns anarray, 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 anarrayof the relevant tokens for a specificUsermodelpublic 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.