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.
Update, November 25, 2026: the kit this series is drawn from now ships the strict version of this flow: accepting an invitation requires a verified email address, the signed link opens a confirmation page (GET no longer mutates anything), and only the POST consumes the invitation. Consumption is one conditional delete statement rather than a check-then-act, and owners can revoke a pending invitation. In one test run of eight concurrent accepts of the same invitation on the default SQLite setup, one accept succeeded and the other seven got 404/410 with no 500s; in a separate accept-versus-revoke race, the revocation won and no membership was granted. That is what those runs showed - MySQL and Postgres are untested, and heavy contention can still produce errors. The downloadable release was updated on November 25; the hosted demo still runs the earlier flow until its next redeploy, and the code below predates the patch.
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}."); } A candid note on the method before the rules: this accepts via GET, because one click from an email should just work. That is a state change on a route that HTTP treats as safe - email link scanners, prefetchers and browser retries all fire GETs. The auth + signed + email-match stack limits what a stray request can do, but it does not change the semantics. The strict design is: GET renders a confirm page, POST performs the accept. The GET version is a convenience tradeoff with real risk attached, not a safe default - and it is the version the kit shipped at first; the November 25 update replaces it with the confirm-page-plus-POST design.
Four rules, each one earned:
Rule 1: auth + signed + verified 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. Verified (see Rule 2) is what makes the email match mean anything.
Rule 2: the email must match, with hash_equals - and matching is not ownership. 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. But the check only compares two strings: the invite's address and the logged-in account's address. It binds the invite to an account claiming that address, which only equals the account owning that address if your app enforces verified email on this route. Laravel ships MustVerifyEmail and a verified middleware for exactly this; the accept route below should include it (['auth', 'verified', 'signed']). Without that, anyone who registers with somebody else's address - unverified - can accept invites meant for that 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. A sequential double-click is then harmless: the invitation row is gone, so the second visit 404s at route-model binding.
A raced double-accept - two requests inside the same milliseconds, both passing the checks before either deletes - is a different beast, and syncWithoutDetaching alone does not save you: both syncs can see "no row yet" and both insert. What actually makes the race converge is the database, so put a unique index on the pivot and say so:
Schema::create('team_user', function (Blueprint $table) { $table->id(); $table->foreignId('team_id')->constrained()->cascadeOnDelete(); $table->foreignId('user_id')->constrained()->cascadeOnDelete(); $table->string('role')->default('member'); $table->timestamps(); $table->unique(['team_id', 'user_id']); // the real double-accept gate }); With the index, the losing insert violates the constraint and one membership row survives. Know that the loser currently gets an unhandled 500 from that violation - correct in outcome, rough in experience; catch UniqueConstraintViolationException and redirect as though they won if you want it clean.
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 a@example.com, log in as b@example.com, 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.
Be honest about what these four tests do not cover: a raced double-accept against the unique index, the expired-invite 410 path, revoking a pending invite (this implementation has no revoke endpoint yet - an owner cannot cancel a sent invite), and verified-email enforcement on the accept route. Each is a real behavior; each deserves its own test when you add the behavior.
The short version
- Invitations are email + role + token + expiry. Expiry is not optional.
- Signed route, auth, verified email, and an email match on accept - the link is a capability, and the match is only as strong as your verification.
- Delete the token on first use; back double-accept convergence with a unique index on the pivot, not with
syncWithoutDetachingalone. - A GET accept route mutates on a safe HTTP method - a convenience tradeoff with real risk attached. A confirm page plus POST is the strict version, and it is what the kit ships now.
- 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 - and test expiry, revocation and the race when you build them.
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.

