I have integrated FCM (Firebase Cloud Messaging) notification with my laravel project.
I have added the method routeNotificationForFcm
in the User
model.
The notification system is working fine when the firebase device token is specified directly in the method, but not working when the token is accessed from database.
The working code added is given below.
public function routeNotificationForFcm()
{
return ['dJQqgKlETpqCB3uxHtfUbL:APA91bFdrcXZMNH0iMjkXMoop_b_nI3xF92DU0P1nrHVQsTDK4w-OH5QR6BsnWIV-wSxSV7avzuBmLVizNyrRcKfAQz6H66JEP9rWKUeIi7m7wEZwRiuW_WdCW_LaZajdFZlxfCUonCL'];
}
The code that is not working is as follows (database query)
public function routeNotificationForFcm()
{
return $this->from('fcm_tokens')->where('user_id', $user->id)->pluck('device_token');
}
The error message showing is The registration token is not a valid FCM registration token
According to Laravel documentation pluck
return Collection
- so you just need to call toArray()
after you called pluck
on query/collection to return array
, as you did previously with mocked token.
public function routeNotificationForFcm()
{
return $this->from('fcm_tokens')->where('user_id', $user->id)->pluck('device_token')->toArray();
}
Also you call for $user->id
but you doesn't have one in this scope.
Solution is simple you need to pass the value or take it from $this
.
public function routeNotificationForFcm()
{
return $this->from('fcm_tokens')->where('user_id', $this->id)->pluck('device_token')->toArray();
}
But personally I'll recommend you to define separate relation for that
public function fcmTokens()
{
return $this->hasMany(FcmToken::class);
}
FcmToken
- is just guess how you named your model.
And then you can reuse it like this to return array
of related tokens for specific User
model
public function routeNotificationForFcm()
{
return $this->fcmTokens()->pluck('device_token')->toArray();
}
In the end, if you structure your code like this you would have general relation and make with this relation you code more flexible.