What is the solution for the following error message?
foreach() argument must be of type array|object, null given
Code
<?php
namespace AppHttpLivewire;
use LivewireComponent;
use AppModelsGovernorate;
use AppModelsDirectorate;
class City extends Component
{
public $directorate = null;
public $governorate = null;
public function render()
{
return view('livewire.city', [
'governorate' => Governorate::get(['name', 'id']),
]);
}
}
@foreach ($governorate as $item)
<option name="form_Cityy" id="form_Cityy" value="{{$item->id}}">
{{$item->name}}
</option>
@endforeach
@if(is_object($governorate))
<option name="form_Cityy" id="form_Cityy">none</option>
@endif
2
Answers
The error you’re encountering, foreach() argument must be of type array|object, null given, suggests that the $governorate variable being passed to your foreach loop is null. This is likely happening because your Livewire component is rendering before the data is available.
To resolve this issue, you can check if $governorate is not null before attempting to iterate over it in your Blade template. Here’s how you can modify your Blade template:
You are passing data to your view that is named the same as a
public
property. Chances are the property data is overwriting the passed data to the view. By only using one of the two, it should work as expected: