Is there an event that triggers when Notification::send()
is called? I want to call a function to send push notification when Notification::send() is called.
I'm creating a comment feature where user can mention other user with format @username, and send notification for every user mentioned.
This is my 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
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
?
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
You can listen for Illuminate\\Notifications\\Events\\NotificationSent
and fire whatever class you like.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.