Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

Showing Progress for Batch of Jobs

Premium
4 min read

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...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

No comments yet…