Laravel Tests - changing Sanctum default guard

When creating an API using Laravel Sanctum for authentication, it may be necessary to test it. In such cases, Sanctum offers the "actingAs" method to authenticate a user.

// Authenticating w. Sanctum on Test Env.
$user = User::factory()->create();

But, by default, when using this method, the user will be authenticated using the "sanctum" guard. And there are cases in that you'll need to change it.

For example, if you are using the package Laravel Permissions from Spatie, and try to run a test using Sanctum authentication and creating some permissions, you'll get the following exception:

The given role or permission should use guard `web, api` instead of `sanctum`.

It happens because, by default, the Laravel Permissions package will use the application predefined guards (web, API), but Sanctum is using the "sanctum" guard instead.

To solve it, just change the Sanctum authentication to use the following code:

// The empty array can be filled with token abilities
Sanctum::actingAs($user, [], 'web');

That is it!

With this simple change, you can define the correct guard when using Sanctum authentication on your tests.

I hope this post is helpful for you. Cheers!

Tiago Rodrigues

by Tiago Rodrigues

Software Developer. Creator of Vemto. Find me on Twitter.


A Desktop Laravel code generator that will power the way you start new Laravel Projects.
More Details