php - Laravel 数据库通知在 Notification::send() 上做一些事情
问题描述
是否有一个事件在Notification::send()
被调用时触发?我想在调用 Notification::send() 时调用一个函数来发送推送通知。
我正在创建一个评论功能,用户可以使用@username 格式提及其他用户,并为提到的每个用户发送通知。
这是我的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));
}
}
这是我的通知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,
];
}
}
这是我发送推送通知的功能。还会有其他控制器。那么我可以在哪里调用这个函数一次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);
}
解决方案
有一部分文档专门针对此主题...
https://laravel.com/docs/6.0/notifications#notification-events
您可以收听Illuminate\Notifications\Events\NotificationSent
并解雇您喜欢的任何课程。
推荐阅读
- c - 将读取文件转换为 C
- wordpress - 修改类别时出现 Wordpress 错误 - 您试图编辑不存在的项目。也许它被删除了?
- c++ - 如何从 CScrollView 中仅删除水平滚动条
- javascript - 底部 div 以垂直滚动占用剩余空间
- ruby - 如何通过 ActiveMerchant::AuthorizeNetCimGateway 在我的客户付款资料中保存名称?
- bash - 有没有办法在 Bash 的另一个命令中使用命令的输入?
- vb.net - 如何在 vb.net 中停止闪烁/闪烁任务栏图标?
- python - 从表中抓取数据,但缺少 tbody 标记
- php - 在 SQL 中找不到数据时显示消息
- sqlite - 如何创建一个用户可以在 sqlite 和 kotlin 上创建自己的表的应用程序