Laravel queue can be used for queuing for example sending push notifications to all users, which otherwise using foreach can put strain on server when it needs to iterate over large number of reciepients.
php artisan make:job SendPushNotification
the above command creates a new file in apps/jobs directory as SendPushNotification, the contents of which can be like
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Notification;
use App\Notifications\FcmPushNotification;
use App\Models\User;
class SendPushNotification implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $title;
protected $body;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($title, $body)
{
$this->title = $title;
$this->body = $body;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$users = User::whereNotNull('fcm_token')->get();
foreach ($users as $user) {
try {
Notification::send($user, new FcmPushNotification($this->title, this->body));
} catch (\Exception $e) {
\Log::error('Error sending push notification: ' . $e->getMessage());
// Optionally, handle token deletion or other logic here
}
}
}
}
then in the controller where it handles the submitted msg/notification to be sent can be like this
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Notification;
use App\Notifications\FcmPushNotification;
use App\Models\User;
use Illuminate\Http\Request;
class SendNotification extends Component
{
public $title = '';
public $body = '';
public function send()
{
// Validation (optional)
$this->validate([
'title' => 'required|min:3',
'body' => 'required|min:5',
]);
// Dispatch the job to send notifications
dispatch(new \App\Jobs\SendPushNotification($this->title, $this->body));
$this->dispatchBrowserEvent('show-alert', ['message' => 'Notification sending initiated!']);
// Reset the form fields
$this->reset(['title', 'body']);
}
public function sendToSpecificUser(Request $request,$userId)
{
$secretKey = $request->input('secret_key');
if ($secretKey !== env('NOTIFICATION_SECRET_KEY')) {
// Authentication failed
abort(403, 'Unauthorized action.');
}
$user = User::where('id', $userId)->whereNotNull('fcm_token')->first();
if ($user) {
$title = env('NEWMESSAGE_ALERT_TITLE', 'New Message Alert');
$body = env('NEWMESSAGE_ALERT', 'You have got a new message from support PUC, please check your app chat.');
Notification::send($user, new FcmPushNotification($title, $body));
\Log::info('Push notification sent to user ID: ' . $userId);
// Additional logic to handle the notification sending...
} else {
\Log::info('User not found or FCM token is null for user ID: ' . $userId);
// Handle the case where the user doesn't exist or doesn't have an FCM token
}
}
public function registerToken(Request $request)
{
$request->validate(['token' => 'required']);
$user = auth()->user();
$user->update(['fcm_token' => $request->token]);
return response()->json(['message' => 'Token registered successfully']);
}
public function render()
{
return view('livewire.send-notification');
}
}
then you need to finally run this command
php artisan queue:work
php artisan queue:restart
Leave a Reply