Level 16
I think it's better to forget() the company_id session instead of updating it to null. That way you can do assertSessionMissing('company_id').
2 likes
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm trying to figure out what I'm doing wrong in my test. Currently my test passes until it hits the assertSessionHas('company_id', null) part of the test. Currently the test is failing due to Session is missing expected key [company_id].
I go through the browser and I see the company_id in the session. Not sure what I"m doing wrong.
/** @test */
public function a_super_admin_who_impersonates_a_company_admin_can_leave_impersonation()
{
$superAdmin = User::factory()->superAdmin()->create();
$user = User::factory()->companyAdmin()->create();
$this->actingAs($superAdmin)
->post(route('impersonate', $user))
->assertSessionHas('company_id', $user->company->id);
$this->assertAuthenticatedAs($user);
$this
->get(route('leave-impersonation'))
->assertRedirect()
->assertSessionHas('company_id', null)
->assertSessionMissing('impersonate');
$this->assertAuthenticatedAs($superAdmin);
}
/**
* Handle the incoming request.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
if (! session()->has('impersonate')) {
abort(403);
}
$impersonator = User::withoutGlobalScope(CompanyScope::class)->find(session('impersonate'));
auth()->login($impersonator);
if ($impersonator->hasRole('super-admin')) {
session()->put('company_id', null);
}
session()->forget('impersonate');
return redirect()->route('user.dashboard');
}
Please or to participate in this conversation.