首页 > 解决方案 > 不能使用 Illuminate\Contracts\Auth\Authenticatable - 这不是一个特征

问题描述

我尝试使用 jwtToken 测试我的应用程序的登录和注销。我迷失了 Laravel Contract 和 Trait。我阅读了很多问题/答案,但解决方案无法在我的代码上运行。我知道合同不像特质那样工作,但它似乎有很大的联系。自3天以来,我一直在寻找出路,但没有成功。

我有这个错误,因为我把 ActingAs 放在我的测试中。

你能帮我吗 ?

我的用户模型:


namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Auth\UserInterface; 
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Role;
use App\Models\UserAddress;


class User extends Authenticatable implements 
    JWTSubject,
    AuthenticatableContract
{
    use Notifiable;
    use SoftDeletes;
    use Authenticatable;

我也尝试不implements AuthenticatableContract 使用我也尝试不使用第一次使用,不使用第二次使用。

我的测试用例:


namespace Tests;

use App\Models\Role;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;


abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    /**
     * @var User
     */
    protected $user;

    public static $admin;

    public static $faker;

    public function setUp(): void
    {
        parent::setUp();

        self::$faker = \Faker\Factory::create('fr_FR');


        self::$admin = \App\Models\User::with('role')
            ->select('*')
            ->join('roles', 'roles.id_role', '=', 'users.id_role')
            ->where('slug', 'admin')
            ->first()->user;

我的帐户测试:


namespace Tests\Feature;

use Carbon\Carbon;
use Tests\TestCase;
use App\Models\Role;
use App\Models\User;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Auth\AuthenticationException;

use Illuminate\Contracts\Auth\Authenticatable;

[...]
 public function testLogout() {

        // $user =  User::inRandomOrder()->firstOrFail();
        // \Log::debug('user->first_name : ' . $user->first_name);

        $this->actingAs(self::$admin)
            ->json('POST', 'api/auth/logout')
            ->assertStatus(200); 
    }```

标签: phplaraveltraitsjwt-authcontract

解决方案


这是不正确的:

class User extends Authenticatable implements 
    JWTSubject,
    AuthenticatableContract
{
    use Notifiable;
    use SoftDeletes;
    use Authenticatable;
}

你不能extend Authenticatableuse Authenticatable

Authenticatable不是特征(如错误所述)。它是一个抽象类,只能扩展。

您可以在此处阅读有关特征和抽象类之间区别的更多信息:PHP 中特征与抽象类之间的区别

删除该use语句应该可以解决您的问题。


推荐阅读