fix(team): prevent 500 after deleting the current team

When a user deletes their current team, the session and cache still
reference the just-deleted team. `refreshSession()` then resolves that
stale team via `currentTeam()`, calls `Team::find()` (which returns
null because the row is gone) and dereferences `$team->id`, leaving the
session without a current team. The subsequent redirect to the team
page assigns the now-null `currentTeam()` to the non-nullable
`Team $team` property in `Team\Index::mount()`, throwing a TypeError
and producing an HTTP 500.

Guard `refreshSession()` against a deleted current team: fall back to
any team the user still belongs to, and if none remain, clear the
stale session reference instead of dereferencing null.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Firsak
2026-05-22 11:06:32 +02:00
parent b124397613
commit d415f3a3d1
+20 -4
View File
@@ -353,14 +353,30 @@ function showBoarding(): bool
function refreshSession(?Team $team = null): void
{
if (! $team) {
if (Auth::user()->currentTeam()) {
$team = Team::find(Auth::user()->currentTeam()->id);
} else {
$team = User::find(Auth::id())->teams->first();
$currentTeam = Auth::user()->currentTeam();
if ($currentTeam) {
// currentTeam() can resolve a stale (just-deleted) team from the
// session/cache, so Team::find() may still return null here.
$team = Team::find($currentTeam->id);
}
if (! $team) {
// Fall back to any team the user still belongs to.
$team = User::find(Auth::id())->teams()->first();
}
}
// Clear old cache key format for backwards compatibility
Cache::forget('team:'.Auth::id());
if (! $team) {
// The user has no team left (e.g. just deleted their current team and
// belongs to no other): clear the stale session reference instead of
// dereferencing null.
session()->forget('currentTeam');
return;
}
// Use new cache key format that includes team ID
Cache::forget('user:'.Auth::id().':team:'.$team->id);
Cache::remember('user:'.Auth::id().':team:'.$team->id, 3600, function () use ($team) {