Moodle | Enrollment-API to get enrolled users based on course id

| By Webner

In one of our Moodle projects, we wanted to retrieve the list of users enrolled in a particular course. One way of getting this data was to query Moodle database and join all the relevant tables as listed below:

1. mdl_context – get records with contextlevel = CONTEXT_COURSE (CONTEXT_COURSE = 50) and instanceid =

2. mdl_role – get record with shortname = ‘student’

3. mdl_role_assignments – get records with contextid = and roleid =

Another way to do this is to use Moodle enrollment API for this as follows:

1. Get course context by using course-id:

$context = get_context_instance(CONTEXT_COURSE, )

2. Use student role-id i.e 5 in Moodle to get list of enrolled users, as below:

$students = get_role_users(5 , $context)

Leave a Reply

Your email address will not be published. Required fields are marked *