首页 > 解决方案 > 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);
}

标签: phplaravelpush-notification

解决方案


有一部分文档专门针对此主题...

https://laravel.com/docs/6.0/notifications#notification-events

您可以收听Illuminate\Notifications\Events\NotificationSent并解雇您喜欢的任何课程。


推荐阅读