When you’re working with form inputs, API data or database records, foreach loop in Laravel keeps your controller logic simple and clear. It’s great for looping through collections, arrays, or requesting data without overengineering the solution.
Even in 2025, developers still trust foreach for quick, readable loops in controllers, especially when performance and reliability are key.
Why foreach Still Works Best in Laravel Controllers
When speed and clarity matter, foreach is still the go-to for Laravel controllers. It lets you process multiple records like users, products or raw API data without relying on heavy collection chaining or extra logic layers.
Use it when you want to act fast and clean:
- Handle API response arrays in one go
- Update user details in bulk
- Filter out bad data before it hits services
- Run conditions without collection transforms
How to Use foreach in a Laravel Controller (Syntax + Example)
The foreach loop lets you go through each item in a collection, making it ideal for controller logic. It’s simple, readable and works with Eloquent results or raw arrays alike.
Here’s how you can loop through a list of users and print their emails:
$customers = App\Models\User::all();foreach ($customers as $customer) {
echo $customer->email;
}
Useful foreach Loop Examples in Laravel Controllers
The foreach loop works great for quick actions inside controllers. Whether you're processing form inputs, updating records or cleaning up expired data it keeps your logic clear and simple.
1. Save Task Submissions from a Form
foreach ($request->input('tasks') as $taskData) { Task::create([
'title' => $taskData['title'],
'due_date' => $taskData['due_date'],
]);
}
2. Update Status for Multiple Customers
foreach ($request->input('customers') as $customer) { Customer::where('uuid', $customer['uuid'])->update([
'status' => $customer['status'],
]);
}
3. Disable Expired Subscriptions Automatically
$subscriptions = Subscription::whereDate('ends_at', '<', now())->get();
foreach ($subscriptions as $subscription) {
$subscription->update(['active' => false]);
}
4. Send Welcome Emails to Newly Registered Users
$users = User::where('created_at', '>=', now()->subDay())->get();
foreach ($users as $user) {
Mail::to($user->email)->send(new WelcomeEmail($user));
}
Did you know?
Over 54% of Laravel developers prefer PhpStorm as their go-to IDE especially when paired with the Laravel Idea plugin for faster more efficient coding.
Validating Each Item in foreach Loops
Laravel doesn’t auto validate arrays of inputs. If you're looping over records like products or users, you’ll need to run validation inside the loop to avoid bad data slipping through.
Example: Validate a List of Products
foreach ($request->input('products') as $index => $product) { $validator = Validator::make($product, [
'name' => 'required|string',
'price' => 'required|numeric',
]);
if ($validator->fails()) {
return response()->json([
'error' => "Validation failed at index $index",
'details' => $validator->errors(),
], 422);
}
}
Avoid These foreach Mistakes in Laravel Controllers
Using foreach the wrong way can lead to broken logic or data errors. Watch out for these common issues when looping inside controllers.
Problem 1: Looping Without Validating Input
foreach ($request->input('users') as $user) { User::create($user); // Will break if fields are missing
}
Fix: Always validate the data before the loop.
$validated = $request->validate([ 'users.*.name' => 'required|string',
'users.*.email' => 'required|email',
]);
Problem 2: Skipping Null Checks
foreach ($data['items'] as $item) { // Fatal if 'items' is null
}
Fix: Add null safety.
foreach ($data['items'] ?? [] as $item) { // safe loop
}
Also Read: The Popular Sites Built With Laravel
Problem 3: No DB Transaction on Bulk Writes
foreach ($orders as $order) { Order::create($order);
}
Fix: Wrap bulk operations in a transaction.
DB::transaction(function () use ($orders) { foreach ($orders as $order) {
Order::create($order);
}
});
Problem 4: Slow Logic Inside the Loop
foreach ($items as $item) { sleep(1); // Or API call inside loop
}
Fix: Move heavy logic outside when possible or batch it.
When to Skip foreach in Laravel Controllers
foreach isn’t ideal for every situation. Use alternatives like collections or service classes when:
- Processing large datasets that require chunking
- Applying map/filter transformations
- Needing to isolate logic for better testability
- Real-time performance is a concern
- Code becomes repetitive or hard to maintain
Conclusion
Use foreach when you want clean, readable loops for processing arrays or Eloquent collections inside controllers. It's fast, reliable and ideal for handling form data, API responses, or quick updates.
But avoid it when you're dealing with large datasets, nested logic or operations that need to be isolated for testability and performance. In such cases, use collections or service layers instead.