public function students($count = false) { //We get the role 'student' $student_role = \Pinom\Models\Role::where('shortname', '=', 'student')->first(); //We look for the role assignments to retrieve it for the $student_role->id $role_assignments = \Pinom\Models\RoleAssignments::where('roleid', '=', $student_role->id)->get(); //Using the query following guidelines from http://stackoverflow.com/a/24593266 answer return \Pinom\Models\Courses::select(array('mdl_role_assignments.userid'))->join('mdl_context', 'mdl_context.instanceid', '=', 'mdl_course.id')->leftJoin('mdl_role_assignments', 'mdl_role_assignments.contextid', '=', 'mdl_context.id')->where('mdl_context.contextlevel', '=', CONTEXT_COURSE)->where('mdl_role_assignments.roleid', '=', $student_role->id)->where('mdl_course.id', '=', $this->id)->get(); }