Summer Sale! All accounts are 50% off this week.

ryan_'s avatar
Level 4

result of relationship does not change

Hey, i have this problem when i dislike a post the database is updated but the test always return false(except when i test each one alone (the like & dislike))


        $post->like($user);
        $this->assertCount(1, $user->likes); // true
        $post->dislike($user);
        $this->assertCount(0, $user->likes); // false it returns 1

I think $user->likes it is not getting the new result. but i don't know why?

0 likes
1 reply
tykus's avatar
tykus
Best Answer
Level 104

Because the first time $user->likes is retrieved, the result is cached. The dislike method call does not affect the cached result. Get a fresh instance of $user so it reloads likes

$post->like($user);
$this->assertCount(1, $user->likes);
$post->dislike($user);
$this->assertCount(0, $user->fresh()->likes);

Or count using the Builder:

$post->like($user);
$this->assertEquals(1, $user->likes()->count());
$post->dislike($user);
$this->assertEquals(0, $user->likes()->count());
2 likes

Please or to participate in this conversation.