Search code examples
phplaravelvoyager

Laravel Invalid argument supplied for foreach


Model Doctor

class Doctor extends Model
{
    public function addresses() {
        return $this->belongsTo(Doctor::class);
    }
}

Model Address

 class Address extends Model
    {
      public function doctors() {
          return $this->hasMany(Address::class);
      }
    }

DoctorsController

class DoctorsController extends Controller
{
    public function index()
    {
        $doctors = Doctor::with('addresses')->get();

        return view('doctors.index',compact('doctors'));
    }
}

Blade

@foreach($doctors as $doctor)
    {{ $doctor->name }}
    @foreach($doctor->addresses as $address)
        {{ $address->city }}
    @endforeach

@endforeach

I have an error

Invalid argument supplied for foreach()

I tried to make a relation between Doctor and Address, but it doesn't work. If i try dd($doctor->addresses) i have null.


Solution

  • does it make sense that a doctor has many addresses and a address has many doctors? basing on your models you do have a many to many relationship between doctors and addresses?

    Why not you can do it this way. a doctor has many addresses? so one to many relationship

    then your models would be like this way.

    Doctor model

    class Doctor extends Model
    {
        public function addresses() {
            return $this->hasMany('App\Address','DoctorId');// you need to indicate the foreign key if you didn't follow the laravel naming convention
        }
    }
    

    address model

    class Address extends Model
    {
        public function doctor() {
            return $this->hasOne('App\Doctor','DoctorId');// you need to indicate the foriegn key if you didn't follow the Laravel naming convention
          }
    }
    

    you controller

    class DoctorsController extends Controller
    {
        public function index()
        {
            $doctors = Doctor::all();//or Doctor::where('something','=','value')->get();
    
            return view('doctors.index',compact('doctors'));
        }
    }
    

    your view

    @foreach($doctors as $doctor)
        {{ $doctor->name }}
        @foreach($doctor->addresses as $address)
            {{ $address->city }}
        @endforeach
    
    @endforeach