So this is a simple taxi dispatch server built in php Laravel that sends out push notifications to the matching online Taxi drivers within the radius of the Customer, using a foreach loop:
foreach ($Providers_active as $key => $Provider) {
(new SendPushNotification)->IncomingRequest($Provider->id);
}
I get all the online Drivers in the Customer's radius using this:
$Providers_active = Provider::with('service')
->select(DB::Raw("(6371 * acos( cos( radians('$latitude') ) * cos( radians(latitude) ) * cos( radians(longitude) - radians('$longitude') ) + sin( radians('$latitude') ) * sin( radians(latitude) ) ) ) AS distance"),'id')
->where('status', 'online')
->orderBy('distance','asc')
->get();
and my IncomingRequest function looks like this:
public function IncomingRequest($provider){
$provider = Provider::where('id',$provider)->with('profile')->first();
return $this->sendPushToProvider($provider->id, "New Ride Request");
}
But since this code gets executed literally in a milisecond, all of the matching drivers get the Push Notification right at the same time. But I'm trying to send the push notifications to them one by one with a delay of perhaps a couple of seconds.
Please note:
But im pretty sure those are not the best ways to do it.
I would put these into a Job Queue. You can rate limit how often a job is processed. So if you want to send one notification every 10 seconds you could do that.
https://laravel.com/docs/8.x/queues#rate-limiting
Here is some example code they have in the docs. This shows perHour() but there is also perMinute(), so if you used perMinute(6) that should send one every 10 seconds.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
RateLimiter::for('backups', function ($job) {
return $job->user->vipCustomer()
? Limit::none()
: Limit::perHour(1)->by($job->user->id);
});
}