Mister M
Mister M

Reputation: 1669

Laravel 5.2 Many to many with custom pivot

I have two tables, 'users' and 'subjects, with custom pivot table 'lecturers_subjects',

table 'lecturers_subjects'

I am trying to build many to many relationship with adding following code in Subject class:

function users(){
        return $this->belongsToMany('App\User','lecturers_subjects','user_id','subject_id');
    }

But then, when i'm trying to display users for certain subjects, it can't find users (array of $subject->users is empty)

$subjects = Subject::all();
foreach($subjects as $subject){
            var_dump($subject->id); //displays 1
            foreach($subject->users as $user){ //array is empty
                var_dump($user->id);
            }
        }

What am I missing?

Upvotes: 1

Views: 142

Answers (1)

KuKeC
KuKeC

Reputation: 4610

Change

function users(){
        //order of keys
        return $this->belongsToMany('App\User','lecturers_subjects','subject_id','user_id');
    }

And that should do it

Upvotes: 2

Related Questions