In this lesson, we'll learn how to display the progress of multiple jobs running in a batch. Laravel provides several ways to do this, but we'll focus on the most straightforward approach using batch objects, which contain all the information we need.
Sending Laravel Jobs as Batch
Let's create an array of jobs to send welcome messages to all users in the system except for the newly registered user.
app/Http/Controllers/Auth/RegisteredUserController.php:
use App\Jobs\SendWelcomeMessage;use Illuminate\Support\Facades\Bus; class RegisteredUserController extends Controller{ // ... public function store(Request $request): RedirectResponse { $request->validate([ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class], 'password' => ['required', 'confirmed', Rules\Password::defaults()], ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); event(new Registered($user)); $jobs = []; foreach (User::where('id', '!=', $user->id)->pluck('id') as $recipient) { $jobs[] = new SendWelcomeMessage($user->id, $recipient); } $batch = Bus::batch($jobs)->dispatch(); Auth::login($user); return redirect(route('dashboard', absolute: false). '?batch_id=' . $batch->id); }}
For the job itself, we've added a small delay to simulate processing time.
app/Jobs/SendWelcomeMessage.php:
use App\Models\Message;use Illuminate\Bus\Batchable;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Contracts\Queue\ShouldQueue; class SendWelcomeMessage implements ShouldQueue{ use Batchable; use Queueable; public function __construct(private readonly int $userId, private readonly int $recipientId) {} public function handle(): void { usleep(50000); Message::create([ 'sender_id' => $this->userId, 'recipient_id' => $this->recipientId, 'title' => 'Welcome!', 'message' => 'Welcome to our world', ]); }}
When a user registers, they are redirected to the dashboard with a...