skip to Main Content

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


  1. 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:

     @if ($governorate)
        @foreach ($governorate as $item)
            <option value="{{ $item->id }}">{{ $item->name }}</option>
        @endforeach
    @endif
    @if (is_null($governorate))
        <option value="none">none</option>
    @endif
    
    Login or Signup to reply.
  2. 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:

    <?php
    
    namespace AppHttpLivewire;
    
    use LivewireComponent;
    use AppModelsGovernorate;
    use AppModelsDirectorate;
    
    
    class City extends Component
    {
        public $directorate = null;
    
        public $governorate = null;
    
        public function mount()
        {
            $this->governorate = Governorate::get(['name', 'id']);
        }
    
        public function render()
        {
            return view('livewire.city');
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search