tylernathanreed's avatar

Eloquent is not Working in Test Cases

I've having the strangest issue. If I do something simple, like this:

groups
    id
    ...

users
    id
    ...

group_user
    group_id
    user_id
    ...

With proper Migrations, Models, etc, like so:

Group.php

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

function attachUser(User $user)
{
    $this->users()->attach($user->id);
}

Calling $group->users works just fine within my actual application. However, when I'm in a Test-Case, this always results to null.

However, if I go and check the database, all of the correct data is there. In fact, if I run the raw DB query:

select * from `groups` inner join `group_user` on `users.id` = `group_user.user_id` where `group_user.group_id` = ?

I get the collection of Users that I was expecting.

So, what gives? Why is this happening?

0 likes
1 reply
tylernathanreed's avatar

No comments?

I'm still having trouble with this issue.

I've made sure that I'm booting Eloquent, so I don't know what the problem could be.

Even if I call $group->users()->toSql(), I get the Database Query that should be getting called.

In fact, I just tried DB::select($group->users()->toSql(), [$group->id]), and the Database returned the expected results.

Please or to participate in this conversation.