The Traits
There're sometimes confusions with the Traits for the User Model.
Sanctum and Passport came with the same Trait, called HasApiToken
.
You may require to change the namespace in the user model from:
from
use Laravel\Sanctum\HasApiTokens;
to
use Laravel\Passport\HasApiTokens;
Testing with PAC
When implementing unit test, you may create a test to create a personal-access-client
too:
In case you hash your secrets in your database, you should set Passport::$hashesClientSecrets
to false
in your test-cases if you need the unhashed password
use RefreshDatabase
/** @test */
public function can_create_a_personal_access_client()
{
Passport::$hashesClientSecrets = false;
$this->artisan(
'passport:client',
['--name' => config('app.name'), '--personal' => null]
)->assertSuccessful();
$this->assertDatabaseCount(PersonalAccessClient::class,1);
}
Because we use the RefreshDatabase
trait, it's usefull to create a helper trait for other tests that may require a personal-access-client
:
<?php
namespace Tests;
use App\Models\User;
use Illuminate\Testing\TestResponse;
trait Helper
{
protected function createPersonalClient()
{
Passport::$hashesClientSecrets = false;
$this->artisan(
'passport:client',
['--name' => config('app.name'), '--personal' => null]
);
// use the query builder instead of the model, to retrieve the client secret
return DB::table('oauth_clients')
->where('personal_access_client','=',true)
->first();
}
}
Now, you can re-use the class for other PAT-Tests:
use RefreshDatabase, Helper;
/** @test */
public function can_issue_a_personal_access_token()
{
$this->createPersonalClient();
$user = User::factory()->create()->createToken('test');
$this->assertInstanceOf(PersonalAccessTokenResult::class, $user);
$this->assertObjectHasAttribute('accessToken', $user);
$this->assertObjectHasAttribute('token', $user);
}