Team invitations in Laravel: signed links, expiring tokens, and the edges that bite
A team invitation feature looks like an afternoon of work: make a row, email a link, add a member on click. The afternoon part is true. The bugs all live in the five percent around it - what happens when the link is forw
A team invitation feature looks like an afternoon of work: make a row, email a link, add a member on click. The afternoon part is true. The bugs all live in the five percent around it - what happens when the link is forwarded, clicked twice, or clicked a month later, and what happens to the person who owns the team.
Here is a complete, small implementation in plain Laravel - no package - and the rules that keep the edges from biting.
The shape
One table. An invitation is an email address, a role, a token, and an expiry:
class TeamInvitation extends Model
{
protected $fillable = ['team_id', 'email', 'role', 'token', 'expires_at'];
protected function casts(): array
{
return ['role' => TeamRole::class, 'expires_at' => 'datetime'];
}
protected static function booted(): void
{
static::creating(function (TeamInvitation $invitation): void {
$invitation->token ??= Str::random(32);
$invitation->expires_at ??= now()->addDays(7);
});
}
public function isExpired(): bool
{
return $this->expires_at->isPast();
}
}
The token defaults in a creating hook so no code path can forget it. Seven days is arbitrary; what is not arbitrary is that there is an expiry at all. An invite that never expires is a permanent capability floating around in someone's inbox.
Sending: owners only, no duplicate members
public function store(Request $request, Team $team): RedirectResponse
{
$validated = $request->validate(['email' => ['required', 'email', 'max:255']]);
abort_unless($request->user()->ownsTeam($team), 403);
abort_if(
$team->members()->where('email', $validated['email'])->exists(),
422,
'That person is already on the team.'
);
$invitation = $team->invitations()->create(['email' => $validated['email']]);
Notification::route('mail', $invitation->email)
->notify(new TeamInvitationNotification(
$invitation,
URL::signedRoute('teams.invitations.accept', $invitation),
));
return back()->with('status', "Invitation sent to {$invitation->email}.");
}
Three deliberate choices:
- Only the owner invites. Membership is money-adjacent (seats, billing), so it stays owner-only. If you widen it later, widen it in one policy, not in the controller.
- Existing members are rejected before a row is created. Checking "is this email already on the team" beats cleaning up duplicate memberships later.
-
The emailed link is a signed route, not a bare URL with the token in it.
URL::signedRouteappends an HMAC of the full URL, so tampering with the invitation id in the path invalidates the link.
Accepting: the link is a capability, so treat it like one
Route::get('teams/invitations/{invitation}', [TeamInvitationController::class, 'accept'])
->middleware(['auth', 'signed'])
->name('teams.invitations.accept');
public function accept(Request $request, TeamInvitation $invitation): RedirectResponse
{
abort_if($invitation->isExpired(), 410, 'This invitation has expired.');
abort_unless(
hash_equals($invitation->email, $request->user()->email),
403,
'This invitation was sent to a different email address.'
);
$invitation->team->addMember($request->user(), $invitation->role);
$invitation->delete();
return redirect()->route('teams.show', $invitation->team)
->with('status', "Welcome to {$invitation->team->name}.");
}
Four rules, each one earned:
Rule 1: auth + signed on the route. The signature proves the link is the one you sent. Auth means the acceptance is tied to an account, not to whoever has the inbox link open.
Rule 2: the email must match, with hash_equals. People forward invite emails constantly - to a colleague, to themselves at another address, into a shared inbox. Without the email check, the forwarded link is a free membership. The check makes the invite personal: the link only works for the account holding the invited address. (If you want forwardable invites, that is a product decision - make it on purpose, not by omission.)
Rule 3: the token dies on first use. $invitation->delete() immediately after addMember. An accepted invite token that stays alive is how you get duplicate memberships when somebody clicks the link twice, or re-opens it from their inbox next week. One row, one use. The matching addMember uses syncWithoutDetaching, so even a raced double-accept converges to one membership row instead of two:
public function addMember(User $user, TeamRole $role = TeamRole::Member): void
{
$this->members()->syncWithoutDetaching([
$user->id => ['role' => $role->value],
]);
}
Rule 4: expiry returns 410, not 404. 410 Gone says "this existed and is over", which is the truth, and it gives the invitee a sensible message instead of a missing-page shrug.
The last-owner problem
Removing members is easy until somebody removes the only owner, or the owner tries to leave. Both directions need an explicit guard:
public function removeMember(Request $request, Team $team, User $user): RedirectResponse
{
abort_unless($request->user()->ownsTeam($team), 403);
abort_if($team->owner_id === $user->id, 422, 'You cannot remove the team owner.');
$team->members()->detach($user->id);
if ($user->current_team_id === $team->id) {
$user->update(['current_team_id' => $user->teams()->value('teams.id')]);
}
return back()->with('status', 'Member removed.');
}
public function leave(Request $request, Team $team): RedirectResponse
{
abort_if(
$request->user()->ownsTeam($team),
422,
'Owners cannot leave their own team. Delete it or transfer ownership first.'
);
// ...
}
An ownerless team is an orphaned billing relationship and an admin nightmare. Pick the rule - "owner must delete or transfer first" - and enforce it in the controller, not in the UI. Hiding the button is not the guard.
The second detail in removeMember is easy to miss: if the removed user was looking at that team, their current_team_id now points at a team they are not on. Reset it to another team of theirs in the same request, or every subsequent page load authorizes against a stale pivot.
Test the edges, not the happy path
The happy path is one test. The edges are the rest:
public function test_a_user_can_create_a_team_and_becomes_its_owner(): void
public function test_an_owner_can_invite_and_the_invitee_can_accept(): void
public function test_an_invitation_only_works_for_the_invited_email(): void
public function test_non_owners_cannot_invite(): void
The third test is the one that pays rent: create the invite for [email protected], log in as [email protected], follow the signed link, assert 403 and assert the membership does not exist. If you only test that acceptance works, you will ship the forwarded-link hole and find out from a user.
The short version
- Invitations are email + role + token + expiry. Expiry is not optional.
- Signed route, auth, and an email match on accept - the link is a capability.
- Delete the token on first use; make member-add idempotent underneath it.
- Guard the last owner in both directions, in the controller.
- Reset
current_team_idwhen you detach anyone. - Write the forwarded-email test before you write the feature announcement.
This article was generated by an AI assistant. The patterns above come from a working Laravel 13 codebase and are covered by its feature tests, but walk the code before you trust it in production - your team's permission model is your own.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.