0

In my app I have a many-to-many relationship between users and organisations,

User

public function organisations()
{
    return $this->belongsToMany('App\Organisation')->withPivot(['owner']);
}

Organisation

public function users()
{
    return $this->belongsToMany('App\User')->withPivot(['owner']);
}

There is a pivot column on this relationship to state whether the user is an owner of the organisation or not.

I am struggling to test the relationship though, my test returns,

Failed asserting that null matches expected 1. Expected :1 Actual :null

Here is my test function,

public function testUserHasOwnershipOfOrganisations()
{
    $userRow = factory(User::class)->create();
    $organisation = factory(Organisation::class)->create();
    $userRow->organisations()->attach($organisation->id, ['owner' => true]);
    $user = User::first();
    $ownOrganisations = $user->organisations()->wherePivot('owner', true);
    $this->assertEquals($organisation->id, $ownOrganisations->first()->organisation_id);
}

The thought process of the above is make a user, make an organisation, create the relationship. Query the first user in the table, get their organisations and make sure the organisation in the organisation relationship as the same ID as the one I just created.

Can anyone tell me why this is not working as I would expect it too?

Thanks

Udders
  • 6,914
  • 24
  • 102
  • 194

1 Answers1

0

UPDATE:

Also check this:

$ownOrganisations->first()->organisation_id

Probably it should be this:

$ownOrganisations->first()->id

/END UPDATE

The only problem I can see is with this line of code:

$user = User::first();

It depends on how your test environment is configured, but there is no assurance that your newly created user is the first in the table. I would suggest to do something more explicit then:

$user = User::find($userRow->id);

Also double check your factories, to assure that they don't add models to this relationship on their own. If they do, you need to take it into account when retrieving your models.

gere
  • 1,600
  • 1
  • 12
  • 19