Back to Error Center
Invalid argument supplied for foreach
Error Message
Warning: Invalid argument supplied for foreach()
Cause
Trying to iterate over a variable that isn't an array or collection. Usually caused by a query returning null instead of a collection.
Solution
Ensure the variable is an array/collection before iterating. Use null coalescing or conditional checks. Eloquent methods return collections, query builder methods may return null.
Code Example
Fix
// Wrong - $result might not be iterable
$result = DB::select('SELECT * FROM posts');
foreach ($result as $row) { /* ... */ }
// Right - check first
$result = DB::select('SELECT * FROM posts');
if (!empty($result)) {
foreach ($result as $row) { /* ... */ }
}
// Eloquent always returns a Collection
$posts = Post::all(); // Collection, always iterable
foreach ($posts as $post) { /* ... */ }
// Use collect() to wrap arrays
$items = collect($dataArray)->filter()->values();
foreach ($items as $item) { /* ... */ }
Debugging Steps
- Check the variable type before the foreach
- Use dd() or dump() to inspect the variable
- Verify the query returns results
- Check if the method returns a Collection or array
Prevention
Always verify data is iterable before looping. Use Eloquent which always returns collections. Add null/empty checks for raw queries.