Skip to content

Instantly share code, notes, and snippets.

@AhmedHdeawy
Created May 10, 2024 03:48
Show Gist options
  • Save AhmedHdeawy/4383bf0e27e8e7d17cee3ff7f64007a9 to your computer and use it in GitHub Desktop.
Save AhmedHdeawy/4383bf0e27e8e7d17cee3ff7f64007a9 to your computer and use it in GitHub Desktop.
Defining and Dispatching a Job for sending mass email notifications during a promotional sale
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Jobs\SendPromotionalSaleEmailJob;
use App\Models\User;
use Illuminate\Http\Request;
class PromotionalSaleController extends Controller
{
public function sendMassEmails(Request $request)
{
SendPromotionalSaleEmailJob::dispatch($request->content);
return redirect()->back()->with('message', 'Emails dispatching started successfully!');
}
}
<?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 App\Models\User;
class SendPromotionalSaleEmailJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(protected string $content)
{
}
public function handle()
{
// Paginate the users or chunk them to process in batches
User::select(['id', 'email'])->chunk(1000, function ($users) {
foreach ($users as $user) {
// Send email to each user
\Mail::to($user->email)->send(new \App\Mail\PromotionalOffer($this->content));
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment