DEV Community

Surya Pratap
Surya Pratap

Posted on

Enrol student in a course programmatically.

Hello there,

I am back with an easiest way to enrol a student in a course programmatically. Just five line of code to get it done.
Try the below code:

Step-1: Must include the below code at the top of your file.

require_once($CFG->dirroot . '/lib/enrollib.php');
Enter fullscreen mode Exit fullscreen mode

Step-2: Put the enrol_user function in your PHP script.

function enrol_user($courseid, $userid){
    global $DB;
    // Enrol the user in the course.
    $studentrole = $DB->get_record('role', array('shortname' => 'student'));
    $maninstance1 = $DB->get_record('enrol', array('courseid' => $courseid, 'enrol' => 'manual'), '*', MUST_EXIST);
    $manual = enrol_get_plugin('manual');
    $manual->enrol_user($maninstance1, $userid, $studentrole->id);
}
Enter fullscreen mode Exit fullscreen mode

Step-3: Call the enrol_user function.

enrol_user($courseid, $userid)
Enter fullscreen mode Exit fullscreen mode

Happy learning!

Top comments (0)