Last Updated: February 25, 2016
·
1.648K
· searsaw

Bulk Adding Roles to a User in Laravel

Laravel doesn't ship with any role management built in. If you have a user and role model set up and already have a user, role, and user_role table created, then you can use the following two functions in your user model to add permissions to a user in bulk based on certain "titles."

Note: This function will need to be edited a bit to match your particular application.

/**
 * Get key in array with corresponding value
 *
 * @return int
 */
private function getIdInArray($array, $term)
{
    foreach ($array as $key => $value) {
        if ($value == $term) {
            return $key;
        }
    }

    throw new UnexpectedValueException;
}

/**
 * Add roles to user to make them a concierge
 */
public function makeEmployee($title)
{
    $assigned_roles = array();

    $roles = array_fetch(Role::all()->toArray(), 'name');

    switch ($title) {
        case 'super_admin':
            $assigned_roles[] = $this->getIdInArray($roles, 'edit_customer');
            $assigned_roles[] = $this->getIdInArray($roles, 'delete_customer');
        case 'admin':
            $assigned_roles[] = $this->getIdInArray($roles, 'create_customer');
        case 'concierge':
            $assigned_roles[] = $this->getIdInArray($roles, 'add_points');
            $assigned_roles[] = $this->getIdInArray($roles, 'redeem_points');
            break;
        default:
            throw new \Exception("The employee status entered does not exist");
    }

    $this->roles()->attach($assigned_roles);
}

I wrote a blog post that describes this in more detail at the following: http://alexsears.com/article/adding-roles-to-laravel-users