Created
May 10, 2024 03:48
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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!'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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