untymage's avatar

Unit test for Many to Many Relationship

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');
});
0 likes
2 replies
camachojua's avatar

I think you have an extra "s" on the users function, maybe it should read:

public function users()
{
    return $this->belongsToMany(User::class);
}
Drfraker's avatar
$role = factory('App\Role')->create();

$this->assertInstanceOf(User::class, $role->users->first()); // You were retrieving a collection of users, which is an instance of an `Eloquent\Collection`, not a `User`

Please or to participate in this conversation.