@bobwurtz I believe the loginAs function requires the actual user object, not just the id.
Try removing ->id after $user in your loginAs function. Like so: loginAs($user))
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have an issue with invalid Laravel login attempts. Sometimes, using the correct email and password, my app returns that Auth::check() === false. I have this check in a middleware, and if the check fails the user is directed back to the login page. In the past, what I have done to get around this is the following:
if (Auth::check() === false) {
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('login');
}
Invalidating the session and regenerating the token 'fixes' the problem by forcing the user to login again. The second login attempt always works. Annoying - but it was a workaround for something that didn't happen that often so I moved on. I've recently started writing browser tests with Dusk and the issue has come up again. None of my Dusk login attempts are successful - they all fail. Below are two basic tests - the first one fails and the second one passes:
<?php
namespace Tests\Browser;
use App\Models\Cafe;
use App\Models\Role;
use App\Models\User;
use App\Models\UserToCafe;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
class LoginTest extends DuskTestCase
{
/** @test */
public function a_user_can_login_correctly()
{
$roleId = Role::where('name', 'cafe_user')->value('id');
$user = User::factory()
->state([
'role_id' => $roleId,
])
->create();
$this->browse(function ($browser) use ($user) {
$browser->loginAs($user->id)
->visit(route('cafe-menu'))
->assertSeeLink('Menu');
});
}
/** @test */
public function a_user_can_login_correctly_v2()
{
$roleId = Role::where('name', 'cafe_user')->value('id');
$user = User::factory()
->state([
'role_id' => $roleId,
])
->create();
$this->browse(function ($browser) use ($user) {
$browser->visit('/login')
->type('email', $user->email)
->type('password', 'password')
->click('button[type="submit"]')
->type('email', $user->email)
->type('password', 'password')
->click('button[type="submit"]')
->assertSeeLink('Menu');
});
}
}
This authentication issue started happening after I upgraded to Laravel 9. I am now on the latest Laravel release (9.8.1). I experience this login error locally, and in staging and production (I am only using Dusk locally - but the authentication error happens to users on all three sites). Most of my users just stay logged in so it's not huge deal in production, but this issue with testing is very annoying. I could use the "double-login" method in the second test for all future tests but I'd like to solve this issue. Does anyone have any idea about what could be going on here? Thank you!
Please or to participate in this conversation.