Using a logged-in User in Tinker
During Laravel testing, we can use the
actingAs() method
to authenticate a user into the testing environment.
class ExampleTest extends TestCase
{
#[Test]
public function authenticated_user_can_see_dashboard(): void
{
$this->actingAs(User::factory()->create())
->get('/dashboard')
->assertOk();
}
}
I have an event in a model that requires the authenticated User:
class Organization extends Model
{
#[\Override]
protected static function booted(): void
{
static::created(static function (Organization $organization) {
OrganizationCreatedEvent::dispatch($organization, Auth::user());
});
}
}
During testing, we use the actingAs() method to fill the Auth::user() model, but what happens when we need to create
an Organization in the tinker shell?
> $o = Organization::factory()->create()
TypeError App\Events\OrganizationCreated::__construct(): Argument #2 ($user) must be of type App\Models\User, null given, called in vendor/laravel/framework/src/Illuminate/Foundation/Events/Dispatchable.php on line 15.
> $this->actingAs($user)
Error Using $this when not in object context.
We can't use $this-> because, like the error message says, we're not in an object.
But it's easy enough to add the user:
> $user = User::factory()->create();
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
= App\Models\User {#8767
name: "Mrs. Candace Runolfsdottir",
email: "wauvot.kiara.borer@example.net",
email_verified_at: "2026-05-08 14:43:37",
#password: "\$2y\$12\$ehsEQzkwABxZiH37PT1zpuQsR5ncLR1A78hEYPYMTAL1gxr..9XV6",
#remember_token: "lnVyiUqw6d",
#two_factor_secret: null,
#two_factor_recovery_codes: null,
two_factor_confirmed_at: null,
updated_at: "2026-05-08 14:43:37",
created_at: "2026-05-08 14:43:37",
id: 4,
}
> app('auth')->guard(null)->setUser($user);
= Illuminate\Auth\SessionGuard {#8687
+name: "web",
}
> $o = Organization::factory()->create()
[!] Aliasing 'Organization' to 'App\Models\Organization' for this Tinker session.
= App\Models\Organization {#9165
name: "Reilly Ltd",
updated_at: "2026-05-08 14:43:52",
created_at: "2026-05-08 14:43:52",
id: 2,
}
Now the only thing I need to do is figure out how to fake or skip a Notification automatically while in the tinker
console.
- ← Previous
My simple Baked Ziti recipe