Search code examples
laravellaravel-sanctum

Testing Laravel Sanctum acting as results in bad method call


I'm trying to test an authenticated API route which only an authenticated user can post to a specific route.

Looking at the Laravel Sanctum docs, I can use the code below to create and authenticate a user:

Sanctum::actingAs(
    factory(User::class)->create(),
    ['*']
);

When I try replicate this, I get an error running the test

BadMethodCallException: Call to undefined method App\User::withAccessToken()

My test code is as follows:

    public function an_authenticated_user_can_add_a_client()
    {
        $user = Sanctum::actingAs(
            factory(User::class)->create(),
            ['*']
        );
        dd($user);
        // $this->post('/api/clients', $this->data());
    }

api.php

Route::middleware('auth:sanctum')->group(function () {

    //Clients
    Route::get('/clients/{client}','ContactsController@show');
    Route::post('/clients','ContactsController@store');
    Route::patch('/clients/{client}','ContactsController@update');
    Route::delete('/clients/{client}','ContactsController@destroy');
});

I don't have the method withAccessToken() in my User class and can't see where this method is coming from or specified anywhere. Any help would be greatly appreciated.


Solution

  • Your User model is missing the HasApiTokens trait, that gives the function you are missing to the User model. Also described in the documentation, under the section Issuing API Tokens.

    use Laravel\Sanctum\HasApiTokens;
    
    class User {
        use HasApiTokens;
    }