Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ahoi's avatar
Level 5

Check user's roles in checkbox

Hello everybody,

I got this array of objects (roles):

Array (2)
0 {id: 2, name: "admin", guard_name: "web", created_at: "2018-10-21 15:39:14", updated_at: "2018-10-21 15:39:14"}
1 {id: 3, name: "super-admin", guard_name: "web", created_at: "2018-10-22 05:16:00", updated_at: "2018-10-22 05:16:00"}

Now I’d like to create some checkboxes that are checked, if the user has one specific role ((`user.rol):

This is the array:


0 {id: 2, name: "admin", guard_name: "web", created_at: "2018-10-21 15:39:14", updated_at: "2018-10-21 15:39:14", …}
1 {id: 3, name: "super-admin", guard_name: "web", created_at: "2018-10-22 05:16:00", updated_at: "2018-10-22 05:16:00", …}

Now I'd like to show checkboxes that are checked, if the user has a role:

<div v-for="role in roles">
                    <label><input class="uk-checkbox" type="checkbox" :value="role"  v-model="user.roles"> {{ role.name }}</label><br />
</div>

Unfortunately this does not work. The checkboxes are not checked :-/

Maybe someone could help me out here? :slight_smile: Thanks in advance :-)

0 likes
2 replies
rawilk's avatar
rawilk
Best Answer
Level 47

This might not be the most efficient way of doing it, but you could do something like this:

<label><input class="uk-checkbox" type="checkbox" :checked="hasRole(role.id)" @input="toggleRole(role.id)">{{ role.name }}</label><br />
data {
     return {
            roleIds: this.user.roles.map(role => role.id)
     };
},

methods: {
     hasRole (roleId) {
          return this.roleIds.includes(roleId);
     },

    toggleRole (roleId) {
         if (this.hasRole(roleId)) {
               return this.roleIds = this.roleIds.filter(id => id !== roleId);
        }

        this.roleIds.push(roleId);
    }
}

Please or to participate in this conversation.