Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joynal's avatar

Many to Many relationship problem

I have many to many relationship between two model Student and Coffer. Here is my model. Student model

public function coffers(){
        return $this->belongsToMany('App\Models\Coffer', 'coffer_student', 'coffer_id', 'student_id')->withPivot('status');
   }

and Coffer Model is

public function students(){
        return $this->belongsToMany('App\Models\Student', 'coffer_student', 'coffer_id', 'student_id')->withPivot('status');
    }

But i can't access

dd($student->coffers);

it's returns empty collection. I manually checked my pivot table have right value.

0 likes
2 replies
davidfaux's avatar
Level 7

I think you have the key order incorrect in the Student model. You need to pass the foreign key first.

public function belongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null){}

//Student model
public function coffers(){
       return $this->belongsToMany('App\Models\Coffer', 'coffer_student', 'student', 'coffer_id')->withPivot('status');
    }

On a side note, you don't need to list the table or key if they follow the convention that the table is derived from the alphabetical order of the related model names (coffer_student), and should have, in this case, the student_id and coffer_id columns.

//Student model
return $this->belongsToMany('App\Models\Coffer')
    ->withPivot('status');
1 like
joynal's avatar

I already solved this. I removed key and table name.

Please or to participate in this conversation.