[英]Laravel database notification do something on Notification::send()
Is there an event that triggers when Notification::send()
is called? 是否在调用Notification::send()
时触发事件? I want to call a function to send push notification when Notification::send() is called. 我想在调用Notification :: send()时调用一个函数来发送推送通知。
I'm creating a comment feature where user can mention other user with format @username, and send notification for every user mentioned. 我正在创建一个评论功能,用户可以使用@username格式提及其他用户,并为每个提及的用户发送通知。
This is my CommentController.php
这是我的CommentController.php
use App\Models\Comment;
use App\Models\User;
use App\Notifications\UserMentioned;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Notification;
class CommentController extends Controller
{
public function store(Request $request)
{
$note = new Comment();
$note->content = $request->content;
$note->save();
preg_match_all('/@([\w\-]+)/', $request->content, $matches);
$username = $matches[1];
$users = User::whereIn('username', $username)->get();
Notification::send($users, new UserMentioned($request->content));
}
}
This is my notification UserMentioned.php
这是我的通知UserMentioned.php
use Illuminate\Notifications\Notification;
class UserMentioned extends Notification
{
public function via($notifiable)
{
return ['database'];
}
public function toDatabase($notifiable)
{
return [
'title' => 'You have been mentioned by ' . auth()->user()->name,
'content' => $notifiable,
];
}
}
This is my function to send push notification. 这是我发送推送通知的功能。 There will be other controllers as well. 也将有其他控制器。 So where can I call this function once for every Notification::send
? 所以我在哪里可以为每个Notification::send
一次调用此函数?
public function sendNotificationFCM(array $deviceKey, String $title, String $body)
{
$url = 'https://fcm.googleapis.com/fcm/send';
$serverKey = 'my-server-key';
$notification = [
'title' => $title,
'body' => $body,
'sound' => 'default',
'badge' => '1',
];
$arrayToSend = [
'registration_ids' => $deviceKey,
'notification' => $notification,
'priority' => 'normal',
];
$json = json_encode($arrayToSend);
$headers = [
'Content-Type: application/json',
'Authorization: key=' . $serverKey,
];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_exec($curl);
curl_close($curl);
}
There is a section of the documentation dedicated to this subject... 文档中有专门针对此主题的部分...
https://laravel.com/docs/6.0/notifications#notification-events https://laravel.com/docs/6.0/notifications#notification-events
You can listen for Illuminate\\Notifications\\Events\\NotificationSent
and fire whatever class you like. 您可以听Illuminate\\Notifications\\Events\\NotificationSent
并触发您喜欢的任何类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.