Mister M Mister M - 2 years ago 181
PHP Question

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

What am I missing?

Answer Source

You have to change your code to get all users by calling method and not property.


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

And that should do it

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download