user(); $userWithRelations = User::with(['organizations', 'banksManaged', 'admins'])->find($user->id); $profiles = $userWithRelations->organizations ->merge($userWithRelations->banksManaged) ->merge($userWithRelations->admins); // Find the index of the profile with this ID $activeProfileId = session('activeProfileId'); $index = $profiles->search(function($item) use ($activeProfileId) { return $item->id == $activeProfileId && get_class($item) == 'App\Models\Bank'; }); // Store the index if found if ($index !== false) { session(['intended_profile_switch' => $index]); } } // Clear any intended URL to prevent redirect loops after profile auth $request->session()->forget('url.intended'); return redirect()->route('bank.login'); } return $next($request); } }