问题
I am quite new to Laravel and couldn't find any practical example of the library https://github.com/Alymosul/laravel-exponent-push-notifications. I want to create a simple Welcome-Notification.
My Notification looks like this:
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use NotificationChannels\ExpoPushNotifications\ExpoChannel;
use NotificationChannels\ExpoPushNotifications\ExpoMessage;
class WelcomeNotification extends Notification
{
use Queueable;
public function __construct(){
}
public function via($notifiable)
{
return [ExpoChannel::class];
}
public function toExpoPush($notifiable)
{
return ExpoMessage::create()
->badge(1)
->title("Hello World!")
->enableSound()
->body("Hello World!");
}
public function toArray($notifiable)
{
return [
];
}
}
I already subscribed a user with the help of the subscribe route (successfully created an DB entry).
Now i want to send the notification to the user:
public function sendNotification(Request $request)
{
$getUserByEmail = User::where('email', 'user@email.com')->first();
$getUserByEmail->notify(new WelcomeNotification());
}
I didn't receive the notification. When using the expo notification tool it works as expected.
Could you please explain to me what am I doing wrong?
回答1:
I figured it out. The problem is, that the library laravel-exponent-push-notifications is sending all notifications without a message-channel to the channel 'Default'.
So it would work if i create the message-channel 'Default' on the device.
Alternatively there are two more options:
Option 1: Create a message channel on the device.
import { Notifications } from 'expo';
if (Platform.OS === 'android') {
await Notifications.createChannelAndroidAsync('chat-messages', {
name: 'Chat messages',
sound: true,
});
}
- Send the notification
$getUserByEmail = User::where('email', 'user@email.com')->first();
$getUserByEmail->notify(new WelcomeNotification());
- The notification should contain the message channel, registered on the device:
public function toExpoPush($notifiable){
return ExpoMessage::create()
->badge(1)
->title("Hello World!")
->enableSound()
->body("Hello World!")
->setChannelId("chat-messages");
}
Option 2:
Change the toArray()-method in the file NotificationChannels\ExpoPushNotifications\
ExpoMessage.php
to something like this:
public function toArray()
{
$returnArray = [
'title' => $this->title,
'body' => $this->body,
'sound' => $this->sound,
'badge' => $this->badge,
'ttl' => $this->ttl,
'channelId' => $this->channelId,
'data' => $this->jsonData,
];
if (strtolower($this->channelId) == 'default' || $this->channelId == '') {
unset($returnArray['channelId']);
}
return $returnArray;
}
When sending notifications to the expo application without a channel, expo is automatically creating a channel and you will receive the notification.
来源:https://stackoverflow.com/questions/60383164/laravel-expo-push-notification-not-receiving-notification-on-android