How do I create a role programmatically in Drupal 8+
//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();
In my case, I wanted to be able to auto-create multiple roles ("clients","managers","salesrep") to work with my custom module.
This is how I auto-create roles programmatically in Drupal.
use Drupal\user\Entity\Role;
function mycustommodule_install() {
//Get all available roles
$get_all_roles=Role::loadMultiple();
//these are the required roles
$required_roles=array("clients","managers","salesrep");
//check if is not already created , create each role
foreach($required_roles as $the_role){
if(!isset($get_all_roles[$the_role])){
$role = Role::create(array('id' => $the_role, 'label' => ucwords($the_role)));
$role->save();
}
}
//
}