Search code examples
phplaravelmany-to-manypivot

Accessing values from laravel Many to Many relationship


I have two tables doctors and specializations and a pivot table doctor_specialities.

In Doctor model, I have defined relationship like this-

public function specializations(){
    return $this->belongsToMany('App\Specialization', 'doctor_specialities', 'speciality_id', 'doctor_id');
}

And in the Specialization model, the relationship is like this-

public function doctors(){
    return $this->belongsToMany('App\Doctor', 'doctor_specialities', 'speciality_id', 'doctor_id');
}

I am getting all the doctors of a specialization like this-

$doctors = Specialization::find($request->specialization)->doctors
                            ->where('city_id', $request->city);

It's working fine. I am getting the correct output.

But now I want to print all the specializations of each doctor but it is returning an empty array.

foreach ($doctors as $doctor) {
    var_dump($doctor->specializations);
}

The output I'm getting is-

object(Illuminate\Database\Eloquent\Collection)[218]
  protected 'items' => 
    array (size=0)
      empty

How can I print specializations of each doctor??


Solution

  • For your updated question, while defining the specializations relation on the Doctor model, the third argument is the foreign key name of the model on which you are defining the relationship (Doctor in your case), while the fourth argument is the foreign key name of the model that you are joining to (Specialization). The relationship should be defined as follows:

    public function specializations(){
        return $this->belongsToMany('App\Specialization', 'doctor_specialities', 'doctor_id', 'speciality_id');
    }
    

    Please refer the documentation here.