Laravel 5 Querying with relations causes "Call to a member function addEagerConstraints() on null" error

Solution 1:

You are missing return statements in the methods that define relations. They need to return relation definition.

Replace

public function roles()
{
    $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');
}

With

public function roles()
{
    return $this->belongsToMany('\App\Role', 'role_user', 'user_id', 'role_id');
}

Solution 2:

You forgot the return in your functions

Do:

return $this->belongsToMany('\App\User', 'fk_role_user', 'role_id', 'user_id');

return $this->belongsToMany('\App\Role', 'fk_user_role', 'user_id', 'role_id');

Solution 3:

You need to use Return for your function's result. If you do not do that, Laravel does not know What should do with that function without any action. Just use like this

return $this->hasOne(xxx, xx, xx);

Enjoy your coding !

Solution 4:

Make sure you have written return in your model function relation.

return $this->hasMany('App\StaffShift','user_id','user_id');