Run Tasks Concurrently in Laravel
Imagine your dashboard needs to calculate the total number of users, orders, and products.
These operations don't depend on each other, so running them sequentially can waste time.
Laravel provides the Concurrency facade to execute independent tasks concurrently.
Basic Usage
use Illuminate\Support\Facades\Concurrency;
use Illuminate\Support\Facades\DB;
[$users, $orders, $products] = Concurrency::run([
fn () => DB::table('users')->count(),
fn () => DB::table('orders')->count(),
fn () => DB::table('products')->count(),
]);
Laravel runs these closures concurrently and returns their results in the same order as the supplied tasks.
Real-World Example
Suppose an admin dashboard needs three independent statistics:
$stats = Concurrency::run([
fn () => User::where('active', true)->count(),
fn () => Order::where('status', 'pending')->count(),
fn () => Product::where('stock', 0)->count(),
]);
return response()->json([
'active_users' => $stats[0],
'pending_orders' => $stats[1],
'out_of_stock_products' => $stats[2],
]);
Instead of waiting for each operation sequentially, Laravel can run them concurrently.
When Should You Use It?
Use Concurrency::run() when:
- Dashboard statistics are independent.
- Multiple expensive calculations can run separately.
- Several independent data sources need processing.
- You want to reduce total waiting time.