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
According to Laravel documentation pluck return
Collection
- so you only need to callafter calling
pluckon the query/collection toArray()
returns anarray
, just like you did before with the mock token.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
.But I personally recommend that you define a separate relationship for this
FcmToken
- Just a guess on how you named your model. You can then reuse it like this to return anarray
of the relevant tokens for a specificUser
modelFinally, if you structure your code like this, you will have a general relationship and use this relationship to make your code more flexible.