Unit test for Many to Many Relationship

Posted 1 month ago by untymage

I'm trying to make sure that my many to many relationship will actually work but what is this error mean?

Failed asserting that Illuminate\Database\Eloquent\Collection Object (...) is an instance of class "App\Role".

My unit test:

$role = factory('App\Role')->create();

$this->assertInstanceOf(User::class, $role->users);

Models:

User

public function roles()
{
    return $this->belongsToMany(Role::class);
}

Role

public function users()
{
    return $this->belongsToMany(User::class);
}

my pivot table:

Schema::create('role_user', function (Blueprint $table) {
        $table->primary(['role_id', 'user_id']);
        $table->unsignedBigInteger('role_id');
        $table->unsignedBigInteger('user_id');
        $table->timestamps();

        $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Please sign in or create an account to participate in this conversation.