API keys
The keys a workspace's own scripts and tools use to call its API: each with a name, what it may do, when it was last used and when it expires, filtered by whether it still works. A new key is shown once, in full, with a button to copy it, and never again. It is one of the settings pages, in the nav the settings page block draws.


A block, not a component: copy the view 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 keys in a table: the name, with the key's last four characters and when it was made under it; what it can do as a badge per scope; when it was last used and when it expires; its status; and Revoke, which asks first (confirm button), for the ones that still work. A key that no longer works is greyed.
-
Filtered by status with navigation tabs, counts on each: links, so the filter is in the address and works with no script.
-
Never the whole key after it is made: the server keeps only a hash of it, so the table shows the last four characters, kept for that purpose at creation.
-
Create key opens a modal: a name, what it can do as a box per scope with a line on each, and when it expires as a select. Errors come back with the modal open on them, the scopes' message said with the boxes:

-
Once made, the page it lands on shows the key in a panel: an alert that it will not be shown again, the key in a read-only input, and a copy button. It is drawn from the session, not a second modal, so it is there with no script and gone on the next load:

-
No keys yet: an empty state with a reason to make one per tool.

Built from
- Page header: the title, its line, and Create key
- Panel, Alert, Input and Copy button: the new key, once
- Tabs: which keys
- Table and Badge: the keys, their scopes and status
- Confirm button: Revoke
- Empty state: no keys yet
- Button and Modal: creating a key
- Checkbox and its group: the scopes, a
checkbox-groupwhose error is said with them - Select: when it expires
The markup
resources/views/settings/api-keys.blade.php
{{--
The keys people create to call Pebblework's API. A key's secret is
shown once, on the page the create redirects to, from the session;
after that only its last four characters are kept to show. The
controller passes $keys (filtered by $status: all, active, expired or
revoked) and $counts.
--}}
@php
$scopes = [
'projects:read' => ['Read projects', 'Names, members and settings of every project.'],
'issues:read' => ['Read issues', 'Issues, comments and their history.'],
'issues:write' => ['Change issues', 'Open, edit, assign and close issues.'],
'members:read' => ['Read members', 'Names, emails and roles.'],
];
$statuses = ['all' => 'All', 'active' => 'Active', 'expired' => 'Expired', 'revoked' => 'Revoked'];
$create = $errors->createKey;
$new = session('newKey');
@endphp
<x-layouts.app title="API keys">
<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="API keys" description="Keys for your own scripts and tools to call the Pebblework API as this workspace.">
<x-slot:actions>
<x-ds::button icon="plus" aria-haspopup="dialog" x-on:click="createOpen = true">Create key</x-ds::button>
</x-slot:actions>
</x-ds::page-header>
@if ($new)
<x-ds::panel :title="$new['name'].' is ready'" icon="key" iconTone="success" body="plain">
<div class="flex flex-col gap-4">
<x-ds::alert tone="warning" title="Copy the key now. You will not see it again.">
We keep only a fingerprint of it. If it is lost, revoke it and create another.
</x-ds::alert>
<div class="flex flex-col gap-2 sm:flex-row sm:items-end">
<x-ds::input id="new-key" label="Your new key" :value="$new['token']" readonly autocomplete="off" spellcheck="false" class="min-w-0 flex-1" />
<x-ds::copy-button target="new-key" label="Copy key" class="self-start sm:self-auto" />
</div>
</div>
</x-ds::panel>
@endif
@if ($counts['all'] === 0)
<x-ds::empty-state icon="key" title="No API keys yet" description="Create one for each script or tool, so you can revoke one without stopping the others.">
<x-slot:action>
<x-ds::button icon="plus" aria-haspopup="dialog" x-on:click="createOpen = true">Create key</x-ds::button>
</x-slot:action>
</x-ds::empty-state>
@else
<div class="flex flex-col gap-4">
<x-ds::tabs label="Which keys" :navigation="true">
@foreach ($statuses as $value => $label)
<x-ds::tab :href="route('settings.api-keys', $value === 'all' ? [] : ['status' => $value])" :active="$status === $value" :count="$counts[$value]">{{ $label }}</x-ds::tab>
@endforeach
</x-ds::tabs>
@if ($keys === [])
<x-ds::empty-state icon="key" :title="'No '.strtolower($statuses[$status]).' keys'" description="Keys show here once they are." />
@else
<x-ds::table label="API keys" :columns="['Name', 'Can', 'Last used', 'Status', ['label' => '', 'width' => 'w-24']]">
@foreach ($keys as $key)
@php $live = $key['status'] === 'active'; @endphp
<x-ds::table-row>
<x-ds::table-cell>
<p @class(['font-medium', 'text-fg' => $live, 'text-fg-muted' => ! $live])>{{ $key['name'] }}</p>
{{-- Never the key: the server keeps only a hash, and the last four characters to show here. --}}
<p class="whitespace-nowrap text-meta text-fg-muted"><code class="font-mono">pw_live_…{{ $key['hint'] }}</code> · Created {{ $key['created'] }}</p>
</x-ds::table-cell>
<x-ds::table-cell>
<div class="flex flex-wrap gap-1">
@foreach ($key['scopes'] as $scope)
<x-ds::badge>{{ $scope }}</x-ds::badge>
@endforeach
</div>
</x-ds::table-cell>
<x-ds::table-cell :nowrap="true">
<p>{{ $key['used'] ?? 'Never used' }}</p>
<p class="text-meta text-fg-muted">{{ $key['expires'] ? ($key['status'] === 'expired' ? 'Expired ' : 'Expires ').$key['expires'] : 'Never expires' }}</p>
</x-ds::table-cell>
<x-ds::table-cell :nowrap="true">
@switch ($key['status'])
@case ('expired')
<x-ds::badge tone="warning">Expired</x-ds::badge>
@break
@case ('revoked')
<x-ds::badge tone="danger">Revoked</x-ds::badge>
@break
@default
<x-ds::badge tone="success" :dot="true">Active</x-ds::badge>
@endswitch
</x-ds::table-cell>
<x-ds::table-cell align="right" :nowrap="true">
@if ($live)
<form method="POST" action="{{ route('api-keys.destroy', $key['id']) }}" class="flex justify-end">
@csrf
@method('DELETE')
<x-ds::confirm-button label="Revoke" question="Revoke {{ $key['name'] }}? It stops working at once." variant="ghost" size="sm" />
</form>
@endif
</x-ds::table-cell>
</x-ds::table-row>
@endforeach
</x-ds::table>
@endif
</div>
@endif
<x-ds::modal open="createOpen" title="Create an API key" description="Give it only what the script needs. You will see the key once, after this." size="md">
<form id="create-key" method="POST" action="{{ route('api-keys.store') }}" class="flex flex-col gap-5">
@csrf
<x-ds::input name="name" label="Name" help="What uses it, like “Deploy bot”." required :value="old('name')" :error="$create->first('name')" />
<x-ds::checkbox-group label="It can" :error="$create->first('scopes')">
@foreach ($scopes as $value => [$label, $help])
<x-ds::checkbox name="scopes[]" :value="$value" :label="$label" :help="$help" :checked="in_array($value, old('scopes', []), true)" />
@endforeach
</x-ds::checkbox-group>
<x-ds::select name="expires" label="Expires" :options="['30' => 'In 30 days', '90' => 'In 90 days', '365' => 'In a year', 'never' => 'Never']" :value="old('expires', '90')" help="An expired key stops working; create a new one to carry on." />
</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-key" size="sm">Create key</x-ds::button>
</x-slot:footer>
</x-ds::modal>
</div>
</div>
</x-layouts.app>
Wire it up
With Laravel Sanctum's personal access tokens. What follows is checked against Sanctum 4's source as far as the notes say; where a part is a judgement or untested, it says so.
What Sanctum gives, and what it does not
createToken($name, $abilities, $expiresAt)on a model with theHasApiTokenstrait returns aNewAccessToken; itsplainTextTokenis{id}|{secret}, and that is the only time the secret exists in plain. Thepersonal_access_tokenstable keeps a SHA-256 hash of the secret.config('sanctum.token_prefix')(SANCTUM_TOKEN_PREFIXin.env) puts a prefix on every secret,pw_live_here, which secret scanners can then spot in a leaked file. Sanctum also appends a CRC32 checksum.- Abilities are strings, stored as JSON;
$request->user()->tokenCan('issues:read')checks one, and theabilitiesandabilitymiddleware check a route. - Each token's
expires_atis checked on every request; an expired token fails as if it were unknown.last_used_atis updated on every use. - Not included: a hint to show the key by (the table has no column for it), and revoking that keeps the row (Sanctum's way is to delete it). Both are a migration away, below. Skip the second and delete on Revoke if you need no Revoked tab.
The migration
Schema::table('personal_access_tokens', function (Blueprint $table) {
$table->string('token_hint', 4)->nullable()->after('token');
$table->timestamp('revoked_at')->nullable()->after('expires_at');
});
A model of your own for the new column, and the check that a revoked key no longer works:
namespace App\Models;
use Laravel\Sanctum\PersonalAccessToken as SanctumToken;
class PersonalAccessToken extends SanctumToken
{
protected function casts(): array
{
return [...parent::casts(), 'revoked_at' => 'datetime'];
}
}
// AppServiceProvider::boot()
use App\Models\PersonalAccessToken;
use Laravel\Sanctum\Sanctum;
Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
// Runs after Sanctum's own checks (the hash, the expiry): $isValid is
// their answer, and this adds one of yours.
Sanctum::authenticateAccessTokensUsing(
fn (PersonalAccessToken $token, bool $isValid) => $isValid && $token->revoked_at === null,
);
If your Sanctum's PersonalAccessToken declares its casts as a $casts
property rather than a casts() method, add to that instead.
Whose keys: the workspace's
The page says the keys call the API "as this workspace", so the tokens
belong to the team: give the Team model the HasApiTokens trait and
create them on it. Sanctum's guard then returns the team from
$request->user() on an API request, since the guard returns whatever
model owns the token. Check this in your app before relying on it:
anything that expects $request->user() to be a User (policies, a
Gate::before, logging) gets a Team on those routes. The other way is
to create each token on the person who made it
($request->user()->createToken(...)) and keep the team's id beside it;
the key then stops working when they leave, which may be what you want.
The routes
use App\Http\Controllers\ApiKeyController;
Route::middleware('auth')->prefix('settings')->group(function () {
Route::get('api-keys', [ApiKeyController::class, 'index'])->name('settings.api-keys');
Route::post('api-keys', [ApiKeyController::class, 'store'])->name('api-keys.store');
Route::delete('api-keys/{key}', [ApiKeyController::class, 'destroy'])->name('api-keys.destroy');
});
And, in routes/api.php, a route the keys call, checking a scope:
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
Route::middleware(['auth:sanctum', CheckAbilities::class.':issues:read'])
->get('issues', fn (Request $request) => $request->user()->issues()->paginate());
(Or alias it as abilities in bootstrap/app.php,
$middleware->alias(['abilities' => CheckAbilities::class]), and write
'abilities:issues:read'.)
Creating a key
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class CreateApiKey extends FormRequest
{
protected $errorBag = 'createKey'; // the view opens the modal when this bag has errors
public const SCOPES = ['projects:read', 'issues:read', 'issues:write', 'members:read'];
public function authorize(): bool
{
return $this->user()->can('manageApiKeys', $this->user()->currentTeam);
}
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:60'],
'scopes' => ['required', 'array'],
'scopes.*' => [Rule::in(self::SCOPES)],
'expires' => ['required', Rule::in(['30', '90', '365', 'never'])],
];
}
public function messages(): array
{
return [
'name.required' => 'Give the key a name, so you know what uses it.',
'scopes.required' => 'Choose at least one thing the key may do.',
];
}
}
namespace App\Http\Controllers;
use App\Http\Requests\CreateApiKey;
use App\Models\PersonalAccessToken;
use Illuminate\Http\Request;
class ApiKeyController
{
public function index(Request $request)
{
$team = $request->user()->currentTeam;
$status = in_array($request->query('status'), ['active', 'expired', 'revoked'], true) ? $request->query('status') : 'all';
$scope = fn (string $status) => fn ($query) => match ($status) {
'revoked' => $query->whereNotNull('revoked_at'),
'expired' => $query->whereNull('revoked_at')->where('expires_at', '<=', now()),
'active' => $query->whereNull('revoked_at')->where(fn ($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now())),
default => $query,
};
$counts = collect(['all', 'active', 'expired', 'revoked'])
->mapWithKeys(fn ($s) => [$s => $team->tokens()->tap($scope($s))->count()])->all();
$keys = $team->tokens()->tap($scope($status))->latest()->get()->map(fn (PersonalAccessToken $t) => [
'id' => $t->id,
'name' => $t->name,
'hint' => $t->token_hint,
'scopes' => $t->abilities,
'created' => $t->created_at->format('j M Y'),
'used' => $t->last_used_at?->diffForHumans(),
'expires' => $t->expires_at?->format('j M Y'),
'status' => match (true) {
$t->revoked_at !== null => 'revoked',
$t->expires_at?->isPast() ?? false => 'expired',
default => 'active',
},
])->all();
return view('settings.api-keys', compact('keys', 'status', 'counts'));
}
public function store(CreateApiKey $request)
{
$days = $request->validated('expires');
$new = $request->user()->currentTeam->createToken(
$request->validated('name'),
$request->validated('scopes'),
$days === 'never' ? null : now()->addDays((int) $days),
);
$new->accessToken->forceFill(['token_hint' => substr($new->plainTextToken, -4)])->save();
// Flashed: in the session for this one redirect, then gone.
return to_route('settings.api-keys')->with('newKey', [
'name' => $new->accessToken->name,
'token' => $new->plainTextToken,
]);
}
public function destroy(Request $request, PersonalAccessToken $key)
{
abort_unless($key->tokenable->is($request->user()->currentTeam), 404);
$key->forceFill(['revoked_at' => now()])->save();
return back()->with('status', $key->name.' revoked. It stops working at once.');
}
}
- The flash holds the secret in your session store until the next
request reads it, a few hundred milliseconds. With the
databaseorfilesession driver that is a row or a file; if that matters, encrypt sessions (SESSION_ENCRYPT=true). - The route model binding for
{key}resolves through the model you registered withusePersonalAccessTokenModelonly if you bind it:Route::model('key', PersonalAccessToken::class)in a service provider. - Pruning:
php artisan sanctum:prune-expired --hours=24on the scheduler deletes keys a day after they expire. It takes the revoked ones only if you delete them yourself, so leave it out if the Expired tab should keep its history.
Live, with Livewire
The secret is kept in a component property for as long as the page is open, never in the session, and shown in the same panel:
namespace App\Livewire;
use App\Http\Requests\CreateApiKey;
use Illuminate\Validation\Rule;
use Livewire\Component;
class ApiKeys extends Component
{
public string $name = '';
public array $scopes = [];
public string $expires = '90';
public ?array $newKey = null;
public bool $createOpen = false;
public function create(): void
{
$this->validate([
'name' => ['required', 'max:60'],
'scopes' => ['required', 'array'],
'scopes.*' => [Rule::in(CreateApiKey::SCOPES)],
'expires' => ['required', Rule::in(['30', '90', '365', 'never'])],
]);
$new = auth()->user()->currentTeam->createToken(
$this->name, $this->scopes, $this->expires === 'never' ? null : now()->addDays((int) $this->expires),
);
$new->accessToken->forceFill(['token_hint' => substr($new->plainTextToken, -4)])->save();
$this->newKey = ['name' => $this->name, 'token' => $new->plainTextToken];
$this->reset('name', 'scopes', 'expires', 'createOpen');
}
public function render()
{
return view('livewire.api-keys', ['keys' => auth()->user()->currentTeam->tokens()->latest()->get()]);
}
}
<div x-data="{ createOpen: $wire.entangle('createOpen') }">
<x-ds::modal open="createOpen" title="Create an API key" size="md">
<form id="create-key" wire:submit="create" class="flex flex-col gap-5">
<x-ds::input name="name" label="Name" wire:model="name" :error="$errors->first('name')" />
<x-ds::checkbox-group label="It can" :error="$errors->first('scopes')">
@foreach ($scopes as $value => [$label, $help])
<x-ds::checkbox name="scopes[]" :value="$value" :label="$label" :help="$help" wire:model="scopes" />
@endforeach
</x-ds::checkbox-group>
<x-ds::input as="select" name="expires" label="Expires" wire:model="expires">
<option value="30">In 30 days</option>
<option value="90">In 90 days</option>
<option value="365">In a year</option>
<option value="never">Never</option>
</x-ds::input>
</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-key" size="sm" wire:loading.attr="disabled" wire:target="create">Create key</x-ds::button>
</x-slot:footer>
</x-ds::modal>
</div>
- The expiry is
ds::input as="select"here:ds::selectpasses no attributes to its<select>,wire:modelincluded. - This form has nothing to compare against, so it has no save bar;
wire:dirtybelongs on the pages that edit something saved.
Phone, keyboard, no script
- Phone: the page header's Create key drops under the title; the tabs scroll sideways when they do not fit; the table keeps its columns and scrolls sideways in its border, the name and its key hint first. The new key's field and Copy key stack.
- Keyboard: the tabs are links, one Tab stop each. Revoke turns into its question on the first press and acts on the second, with Escape to back out. Create key opens the modal with focus in it; Tab moves through the name, each scope's box and the expiry, and Escape closes it. Copy key says "Copied" to a screen reader as well as on the button.
- No script: the tabs are links, and the new key is in the page, to be selected and copied by hand; the copy button needs the script. Create key needs Alpine, as the modal does, and so does Revoke: a confirm button fails safe, its action unreachable without the script. A page that must work with none puts the create form on a page of its own and gives Revoke a page that asks, both plain forms.
From the package repo: edit this page on GitHub.