Roles and permissions

The roles a workspace has and what each may do: the built-in four and a custom one, listed with what they are for and how many members hold them, and below, a grid of permissions by role, grouped by area, a box per permission and a box per area that sets the lot. The owner's column is locked on. It is one of the settings pages, in the nav the settings page block draws.

Roles and the permissions grid, light and dark

Roles and permissions on a phone, one role at a time, light and dark

A block, not a component: copy the views below into your app. It is a page in the sidebar shell, beside the settings nav from the settings page block.

What it shows

  • The roles, a panel row each: name, a line on what it is for, and how many members hold it; a custom role has a badge and a Delete that asks first (confirm button) and says where its members go.

  • The grid is a real table: a column header per role, a row header per permission, and a body per area (Projects, Issues, Members, Billing) whose first row is the area's own. A screen reader says the row and column at every box, and each checkbox is named in full too: "Editors can delete projects".

  • An area's box sets every box under it for that role; a box under it sets the area's box on, off or mixed (Editors, above, have three of the four Projects permissions). The server works out which area boxes are mixed; the mark itself is a DOM property, which Alpine sets as it starts.

  • The owner's column is ticked and disabled, with the reason in a line above the grid that each of its boxes points to. Its boxes have no name, so they post nothing; the server would ignore them anyway.

  • The head and the first column stick (stickyHead, stickyFirst) while the grid scrolls inside a capped height, so a role and a permission are always in sight, with a shadow once something has scrolled under them.

  • One save for the whole grid, with a save bar that comes up on the first change:

    Viewers given every Projects permission, light and dark

  • Create role opens a modal: a name, a line, and a role to copy the permissions of, or none. A name already taken comes back with the modal open on its error:

    Create role with a taken name, light and dark

Built from

  • Page header: the title, its line, and Create role
  • Panel: the roles, a row each, and the grid
  • Badge: Custom
  • Confirm button: deleting a custom role
  • Table and Checkbox: the grid, each area's boxes synced by the checkbox group's x-ds-check-all
  • Icon: the lock by the owner's note
  • Input: the role a phone shows, and the new role's name and line
  • Select: the role to start from
  • Save bar: the grid
  • Button and Modal: creating a role

The markup

resources/views/settings/roles.blade.php

{{--
    The roles and what each may do. The controller passes $roles (key =>
    name, plural, description, members, custom), $permissions (area =>
    permission => [row header, words]) and $grants (role => permissions).
    The owner's are fixed, so they are drawn locked and never posted.
--}}
@php
    $copyFrom = collect($roles)->except('owner')->map(fn ($role) => $role['name'])->all();
    $create = $errors->createRole;
@endphp

<x-layouts.app title="Roles and permissions">
    <div class="flex flex-col gap-6 lg:flex-row lg:gap-10">
        <x-settings.nav />

        <div x-data="{ createOpen: @js($create->any()) }" class="flex min-w-0 flex-1 flex-col gap-6">
            <x-ds::page-header title="Roles and permissions" description="What each role can do. A member has one role.">
                <x-slot:actions>
                    <x-ds::button icon="plus" aria-haspopup="dialog" x-on:click="createOpen = true">Create role</x-ds::button>
                </x-slot:actions>
            </x-ds::page-header>

            <x-ds::panel title="Roles">
                @foreach ($roles as $key => $role)
                    <x-ds::panel-row>
                        <div class="min-w-0 flex-1">
                            <p class="flex flex-wrap items-center gap-2 font-medium text-fg">
                                {{ $role['name'] }}
                                @if ($role['custom'])
                                    <x-ds::badge tone="accent">Custom</x-ds::badge>
                                @endif
                            </p>
                            <p class="text-meta text-fg-muted">{{ $role['description'] }}</p>
                        </div>
                        <p class="shrink-0 text-meta text-fg-muted">{{ $role['members'] }} {{ Str::plural('member', $role['members']) }}</p>
                        @if ($role['custom'])
                            <form method="POST" action="{{ route('roles.destroy', $key) }}">
                                @csrf
                                @method('DELETE')
                                <x-ds::confirm-button question="Delete {{ $role['name'] }}? Its members become Viewers." variant="ghost" size="sm" />
                            </form>
                        @endif
                    </x-ds::panel-row>
                @endforeach
            </x-ds::panel>

            <form
                id="permissions"
                method="POST"
                action="{{ route('permissions.update') }}"
                x-data="{ shown: 'editor' }"
            >
                @csrf
                @method('PUT')
                <x-ds::panel title="Permissions" body="plain">
                    {{-- A phone has no room for every role: one at a time, chosen here. Only where a script can switch it. --}}
                    <x-ds::input as="select" label="Show the permissions of" x-model="shown" class="mb-4 md:hidden [@media(scripting:none)]:hidden">
                        @foreach ($roles as $key => $role)
                            <option value="{{ $key }}" @selected($key === 'editor')>{{ $role['plural'] }}</option>
                        @endforeach
                    </x-ds::input>

                    {{-- Each area's tbody syncs its boxes (x-ds-check-all, in the matrix) before the change reaches the save bar. --}}
                    <x-roles.matrix :roles="$roles" :permissions="$permissions" :grants="$grants" shown="editor" />
                </x-ds::panel>
                <x-ds::save-bar message="Permissions not saved yet" />
            </form>

            <x-ds::modal open="createOpen" title="Create a role" description="Name it for what the people in it do." size="md">
                <form id="create-role" method="POST" action="{{ route('roles.store') }}" class="flex flex-col gap-5">
                    @csrf
                    <x-ds::input name="name" label="Name" required :value="old('name')" :error="$create->first('name')" />
                    <x-ds::input as="textarea" name="description" label="Description" help="One line, shown beside the role." :rows="2" :error="$create->first('description')">{{ old('description') }}</x-ds::input>
                    <x-ds::select name="copy_from" label="Start from" help="Copies that role’s permissions; change them after." :options="$copyFrom" :value="old('copy_from')" placeholder="Nothing: every box off" />
                </form>

                <x-slot:footer>
                    <x-ds::button variant="ghost" size="sm" x-on:click="createOpen = false">Cancel</x-ds::button>
                    <x-ds::button type="submit" form="create-role" size="sm">Create role</x-ds::button>
                </x-slot:footer>
            </x-ds::modal>
        </div>
    </div>
</x-layouts.app>

resources/views/components/roles/matrix.blade.php

{{--
    Permissions by role: a real table, one body per area, with a row header
    for every permission and a column header for every role, so a screen
    reader says both; each box is also named in full ("Editors can delete
    projects"). Each area's first row has a box per role that sets the
    whole area, mixed when the area is part granted. The owner's column is
    locked on. Posts permissions[role][] for every role but the owner's.

    The head is the table's `head` slot, since a column per role is hidden
    on a phone, and the bodies are the slot's own tbody elements, one per
    area. stickyHead and stickyFirst keep the roles and the permissions in
    view; the height is capped so the rows scroll under the head.
--}}
@props(['roles', 'permissions', 'grants', 'shown'])

@php
    // Server-drawn, so a phone shows one role from the first paint; only
    // where scripts run, since without one nothing could switch it.
    $hide = '[@media(scripting:enabled)]:max-md:hidden';
    $hidden = fn (string $role) => $role === $shown ? '' : $hide;
    $toggle = fn (string $role) => "{ '{$hide}': shown !== '{$role}' }";
@endphp

<p id="owner-locked" class="mb-3 flex items-center gap-1.5 text-meta text-fg-muted">
    <x-ds::icon name="lock-closed" size="4" />
    Owners can do everything, and that cannot be changed.
</p>

<x-ds::table label="Permissions by role" :stickyHead="true" :stickyFirst="true" class="max-h-[34rem]">
    <x-slot:head>
        <tr>
            <th scope="col" class="px-4 py-3 text-left text-overline uppercase text-fg-muted">Permission</th>
            @foreach ($roles as $key => $role)
                <th scope="col" class="w-24 px-4 py-3 text-center text-overline uppercase text-fg-muted {{ $hidden($key) }}" x-bind:class="{{ $toggle($key) }}">{{ $role['name'] }}</th>
            @endforeach
        </tr>
    </x-slot:head>

    @foreach ($permissions as $area => $rows)
        {{-- An area's box sets every box under it; any box sets its area's box: on, off or mixed. --}}
        <tbody class="border-t border-divider" x-data x-ds-check-all>
            <tr class="bg-surface-subtle">
                <th scope="rowgroup" class="bg-surface-subtle px-4 py-2 text-left text-body font-medium text-fg">{{ $area }}</th>
                @foreach ($roles as $key => $role)
                    @php
                        $on = count(array_intersect(array_keys($rows), $grants[$key] ?? []));
                        $locked = $key === 'owner';
                    @endphp
                    <x-ds::table-cell align="center" :class="$hidden($key)" x-bind:class="{{ $toggle($key) }}">
                        <x-ds::checkbox
                            :label="$role['plural'].' can do everything under '.$area"
                            :hideLabel="true"
                            :checked="$locked || $on === count($rows)"
                            :indeterminate="! $locked && $on > 0 && $on < count($rows)"
                            :disabled="$locked"
                            :aria-describedby="$locked ? 'owner-locked' : null"
                            :data-ds-check-all="$locked ? null : $key"
                            :data-role="$key"
                            class="justify-center"
                        />
                    </x-ds::table-cell>
                @endforeach
            </tr>
            @foreach ($rows as $permission => [$title, $can])
                <x-ds::table-row :hover="false" class="border-t border-divider">
                    <x-ds::table-cell :rowHeader="true" :nowrap="true" class="ps-8">{{ $title }}</x-ds::table-cell>
                    @foreach ($roles as $key => $role)
                        @php $locked = $key === 'owner'; @endphp
                        <x-ds::table-cell align="center" :class="$hidden($key)" x-bind:class="{{ $toggle($key) }}">
                            <x-ds::checkbox
                                :name="$locked ? null : 'permissions['.$key.'][]'"
                                :value="$permission"
                                :label="$role['plural'].' can '.$can"
                                :hideLabel="true"
                                :checked="$locked || in_array($permission, $grants[$key] ?? [], true)"
                                :disabled="$locked"
                                :aria-describedby="$locked ? 'owner-locked' : null"
                                data-permission
                                :data-ds-check-item="$locked ? null : $key"
                                :data-role="$key"
                                class="justify-center"
                            />
                        </x-ds::table-cell>
                    @endforeach
                </x-ds::table-row>
            @endforeach
        </tbody>
    @endforeach
</x-ds::table>

Wire it up

The routes

use App\Http\Controllers\RoleController;

Route::middleware('auth')->prefix('settings')->group(function () {
    Route::get('roles', [RoleController::class, 'index'])->name('settings.roles');
    Route::post('roles', [RoleController::class, 'store'])->name('roles.store');
    Route::delete('roles/{role}', [RoleController::class, 'destroy'])->name('roles.destroy');
    Route::put('permissions', [RoleController::class, 'permissions'])->name('permissions.update');
});

Where the permissions live

The list of permissions is code, not data: it is what your policies and gates check, so a permission no code checks would be a box that does nothing. Keep it in one place, grouped as the grid shows it:

// config/permissions.php
return [
    'Projects' => [
        'projects.view' => ['See projects', 'see projects'],
        'projects.create' => ['Create projects', 'create projects'],
        'projects.edit' => ['Edit projects', 'edit projects'],
        'projects.delete' => ['Delete projects', 'delete projects'],
    ],
    'Issues' => [
        'issues.create' => ['Open issues', 'open issues'],
        'issues.assign' => ['Assign issues', 'assign issues'],
        'issues.close' => ['Close issues', 'close issues'],
        'issues.delete' => ['Delete issues', 'delete issues'],
    ],
    // Members, Billing …
];

The grants are data: a roles table (team_id, key, name, description, custom, and permissions as a json column cast to an array). A check is then one gate for all of them:

// AppServiceProvider::boot()
Gate::before(function (User $user, string $ability) {
    if (! str_contains($ability, '.')) {
        return null;   // not one of ours: leave it to the policies
    }

    $membership = $user->currentMembership;

    return $membership->role === 'owner' || in_array($ability, $membership->roleModel->permissions, true)
        ? true
        : null;
});

Returning null rather than false lets a policy still say yes for its own reasons (say, the author may always edit their own issue). Then @can('projects.delete') and $this->authorize('issues.close') read the grid.

Saving the grid

Every role but the owner's posts permissions[role][]. A role with every box off posts nothing at all, so read the roles you have, not the ones that arrived:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdatePermissions extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('members.roles');
    }

    public function rules(): array
    {
        $every = collect(config('permissions'))->flatMap(fn ($area) => array_keys($area))->all();

        return [
            'permissions' => ['array'],
            'permissions.*' => ['array'],
            'permissions.*.*' => [Rule::in($every)],
        ];
    }
}
namespace App\Http\Controllers;

use App\Http\Requests\CreateRole;
use App\Http\Requests\UpdatePermissions;
use App\Models\Role;
use Illuminate\Http\Request;

class RoleController
{
    public function permissions(UpdatePermissions $request)
    {
        $team = $request->user()->currentTeam;

        $team->roles()->where('key', '!=', 'owner')->get()->each(fn (Role $role) => $role->update([
            'permissions' => $request->input("permissions.{$role->key}", []),
        ]));

        return back()->with('status', 'Permissions saved.');
    }

    public function store(CreateRole $request)
    {
        $team = $request->user()->currentTeam;
        $from = $request->validated('copy_from') ? $team->roles()->firstWhere('key', $request->validated('copy_from')) : null;

        $team->roles()->create([
            'key' => str($request->validated('name'))->slug(),
            'name' => $request->validated('name'),
            'description' => $request->validated('description'),
            'custom' => true,
            'permissions' => $from?->permissions ?? [],
        ]);

        return back()->with('status', 'Role created.');
    }

    public function destroy(Request $request, Role $role)
    {
        abort_unless($role->team_id === $request->user()->currentTeam->id && $role->custom, 404);

        $role->members()->update(['role' => 'viewer']);
        $role->delete();

        return back()->with('status', $role->name.' deleted. Its members are Viewers now.');
    }
}
class CreateRole extends FormRequest
{
    protected $errorBag = 'createRole';   // the view opens the modal when this bag has errors

    public function authorize(): bool
    {
        return $this->user()->can('members.roles');
    }

    public function rules(): array
    {
        $team = $this->user()->currentTeam;

        return [
            'name' => ['required', 'string', 'max:40', Rule::unique('roles', 'name')->where('team_id', $team->id)],
            'description' => ['nullable', 'string', 'max:120'],
            'copy_from' => ['nullable', Rule::exists('roles', 'key')->where('team_id', $team->id)->whereNot('key', 'owner')],
        ];
    }

    public function messages(): array
    {
        return ['name.unique' => 'There is already a role called :input.'];
    }
}

Live, with Livewire

The grid binds to an array of arrays, wire:model.live="grants.editor" on each of a role's boxes, which Livewire keeps as the list of the ticked values. An area's box asks the server to set its row, and reads its own state from $wire, so it follows every change, the mixed mark included:

namespace App\Livewire;

use Livewire\Component;

class Permissions extends Component
{
    public array $grants = [];

    public function mount(): void
    {
        $this->grants = auth()->user()->currentTeam->roles()
            ->where('key', '!=', 'owner')->pluck('permissions', 'key')->all();
    }

    // An area's box: all on if any is off, else all off.
    public function toggleArea(string $role, string $area): void
    {
        $keys = array_keys(config("permissions.{$area}"));
        $on = array_intersect($keys, $this->grants[$role]);

        $this->grants[$role] = count($on) === count($keys)
            ? array_values(array_diff($this->grants[$role], $keys))
            : array_values(array_unique([...$this->grants[$role], ...$keys]));
    }

    public function save(): void
    {
        // As in UpdatePermissions, then each role's update().
    }

    public function render()
    {
        return view('livewire.permissions');
    }
}
{{-- In the matrix, the area's box per role. `indeterminate` is a DOM
     property that no attribute sets and a morph does not touch, so the box
     sets its own from $wire. --}}
<x-ds::checkbox :label="$role['plural'].' can do everything under '.$area" :hideLabel="true"
    wire:click="toggleArea('{{ $key }}', '{{ $area }}')"
    x-data="{ keys: {{ Js::from(array_keys($rows)) }} }"
    x-effect="const on = keys.filter((k) => $wire.grants['{{ $key }}'].includes(k)).length;
              $el.checked = on === keys.length;
              $el.indeterminate = on > 0 && on < keys.length" />

{{-- and each permission's: --}}
<x-ds::checkbox :value="$permission" :label="$role['plural'].' can '.$can" :hideLabel="true"
    wire:model.live="grants.{{ $key }}" />

{{-- at the foot of the form: --}}
<x-ds::save-bar :dirty="false" wire:dirty.attr="data-ds-dirty" wire:target="grants"
    x-on:discard="$wire.$refresh()" message="Permissions not saved yet" />

Drop x-ds-check-all from the matrix's tbody (and the data-ds-check-* marks) when Livewire draws the area boxes: the two would both set them.

Phone, keyboard, no script

  • Phone: the grid shows one role at a time, chosen from a select above it ("Show the permissions of"), beside the permission names; the columns are hidden by a class the server draws, so the first paint is already one column, and Alpine swaps it as the select changes. Hidden columns' boxes still post, so saving from a phone keeps every role's grants. The roles' rows wrap.
  • Keyboard: each box is a Tab stop, row by row (an area's row of boxes, then each of its permissions'), across the roles; Space ticks. The owner's boxes are disabled and skipped. Create role opens the modal with focus in it; Escape or Cancel closes it.
  • No script: the grid is a form of plain checkboxes with a Save and a Discard under it, and every column is shown, a phone scrolling the table sideways (the role select is hidden, since nothing could act on it). The area boxes do not set their rows without the script, and the mixed mark is not shown, since it needs a line of script: a part-granted area's box reads as off. Each box under an area still posts as it is. Create role needs Alpine, as the modal does, and so does deleting a custom role (a confirm button fails safe, unreachable without its script).

From the package repo: edit this page on GitHub.

Was this page helpful?