Reputation: 23
I passed array to Delete route in Laravel and then in this part of code
foreach ($request->input('publicIds') as $node)
print($node);
I got this error
Invalid argument supplied for foreach() in file
Upvotes: 0
Views: 240
Reputation: 29258
If you're going to use a $request->input()
in a foreach()
, be sure to include a fallback if nothing is passed. If nothing is passed, $request->input()
is null
, and foreach(null as $node)
is not valid.
If you add a fallback, it will use that instead (in your case, an array):
$request->input('publicIds') // `null`
$request->input('publicIds', []) // `[]`
So, to make your code type-safe for a foreach()
, do the following:
foreach ($request->input('publicIds', []) as $node) {
print($node);
}
In scenarios where $request->input('publicIds')
is null
, it will fallback to an array. If scenarios where $request->input('publicIds')
is already an array, the fallback will be skipped (as it is already an array), and your code is now safe.
Upvotes: 1