Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the user role using user id in moodle

Tags:

php

moodle

I am new to Moodle and I have the following code:

$userDetails = $DB->get_record('user', array('id' => $singleuser->userid)); 
    var_dump($userDetails);
    echo $userDetails->firstname." ".$userDetails->lastname

It is having the details of user table in Moodle. How can I find the role like Teacher, Admin, student?

Here I am having the userids $singleuser->userid . I am printing Users full name . I need the role along with it like the following:

echo $userDetails->firstname." ".$userDetails->lastname.$role.

How can I find role? Please guide me.

Moodle Version: 2.9.1

like image 382
Santhucool Avatar asked Oct 17 '25 21:10

Santhucool


1 Answers

You need to know where in Moodle you are asking for the role. Moodle does not (usually) have a global concept of a 'student' or 'teacher' - a teacher is a teacher on a specific course, a student is a student on a particular course.

Assuming you know the id of the course where you want to display the role(s) for, you can write the following:

$rolestr = array();
$context = context_course::instance($courseid);
$roles = get_user_roles($context, $singleuser->userid);
foreach ($roles as $role) {
    $rolestr[] = role_get_name($role, $context);
}
$rolestr = implode(', ', $rolestr);
echo "The users roles are {$rolestr} in course {$courseid}";
like image 166
davosmith Avatar answered Oct 20 '25 12:10

davosmith