簡體   English   中英

Laravel數據庫通知在Notification :: send()上執行某些操作

[英]Laravel database notification do something on 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並觸發您喜歡的任何類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM