Courses

Queues in Laravel 12

Showing Progress for Batch of Jobs

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Using batch information to track job progress in the application UI
- Retrieving batch information with Bus::findBatch() method
- Accessing batch properties like processedJobs(), totalJobs, and progress() to display completion status
- Implementing automatic refresh with JavaScript to see real-time progress updates

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 15 lessons of this course? (46 min read)

You also get:

  • 76 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord