Skip to content

actingAs makes user available without specifying guard in controller #43346

Closed
@WouterFlorijn

Description

@WouterFlorijn
  • Laravel Version: 8.78.1
  • PHP Version: 8.1.8
  • Database Driver & Version: MySQL

Description:

When using actingAs($user, 'some-guard') in endpoint tests, there is no need to specify a guard in the relevant controller method when calling e.g. $request->user(). E.g., when using api authentication for routes outside of auth:api middleware, $request->user() will return a user when actingAs is used in tests, but when running the actual application, it returns null. This leads to false negatives in tests that are hard to debug.

Steps To Reproduce:

I want an endpoint with optional authentication, so add the route without auth:api middleware in routes/api.php.

Route::post('some-endpoint', ...)

In a test, call:

$this->actingAs($user, 'api')->json('POST', 'some-endpoint')

In matching controller method:

$request->user(); // returns User instance, but should return null because the api guard isn't specified.

When running the same in production, $request->user() returns null. Instead, I need to use $request->user('api')

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions