Skip to content

Commit

Permalink
add likeCount method to Likeable trait
Browse files Browse the repository at this point in the history
  • Loading branch information
Mohammad Nourinik committed Oct 24, 2017
1 parent 6493abf commit 4c9f639
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ $book->likes()->where('type', 'bookmark')
$book->liked(); // check if currently logged in user liked the book
$book->liked($myUserId);

$book->likeCount($type); // determine number of likes for given $type (default type is 'like')

Article::whereLikedBy($myUserId) // find only books where user liked them
->with('likeCounter') // highly suggested to allow eager load
->get();
Expand Down
11 changes: 11 additions & 0 deletions src/Likeable.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,17 @@ public function liked($guard = null, $type = 'like')
->exists();
}

public function likeCount($type = 'like')
{
$counter = $this->likeCounter()->where('type', $type)->first();

if ($counter) {
return $counter->count;
} else {
return 0;
}
}

/**
* Private. Increment the total like count stored in the counter.
*
Expand Down
31 changes: 31 additions & 0 deletions tests/CommonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,37 @@ public function testDoubleLikeOneUnlikeSpecificUser()
$this->assertEquals(1, $stub->likeCount);
}

public function testLikeCount()
{
$stub = $this->createRandomStub();
$user = $this->createRandomUser();
$this->actingAs($user);

$stub->like();

$this->assertEquals(1, $stub->likeCount());
}

public function testLikeCountWithType()
{
$stub = $this->createRandomStub();
$user = $this->createRandomUser();
$this->actingAs($user);

$stub->like(null, 'bookmark');
$stub->like();

$this->assertEquals(1, $stub->likeCount('bookmark'));
$this->assertEquals(1, $stub->likeCount());
}

public function testLikeCountZero()
{
$stub = $this->createRandomStub();

$this->assertEquals(0, $stub->likeCount());
}

public function testWhereLikedBy()
{
$stubs = [
Expand Down

0 comments on commit 4c9f639

Please sign in to comment.