【问题标题】:Cannot use Illuminate\Contracts\Auth\Authenticatable - it is not a trait不能使用 Illuminate\Contracts\Auth\Authenticatable - 这不是一个特征
【发布时间】:2020-07-28 17:49:33
【问题描述】:

我尝试使用 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); 
    }```

【问题讨论】:

    标签: php laravel traits jwt-auth contract


    【解决方案1】:

    这是不正确的:

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

    你不能extend Authenticatableuse Authenticatable

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

    您可以在此处阅读有关特征和抽象类之间区别的更多信息:Difference between Trait and an Abstract Class in PHP

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

    【讨论】:

    • 谢谢!这是工作(几乎)。我没有删除测试文件中的use Authenticable。我只需要用Interface [...] AuthenticatableContract not found 解决另一个错误。会更容易解决。
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2016-09-11
    • 2021-10-19
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多