diff --git a/README.md b/README.md index f4f317f..b498eca 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ foreach($likers as $user) { // all $user->likes()->count(); -// short version +// short way $user->totalLikes; // with type @@ -109,6 +109,9 @@ $user->likes()->withType(Post::class)->count(); // likers count $post->likers()->count(); + +// short way +$post->totalLikers ``` List with `*_count` attribute: diff --git a/src/Traits/Likeable.php b/src/Traits/Likeable.php index 36e7c8b..d63d7aa 100644 --- a/src/Traits/Likeable.php +++ b/src/Traits/Likeable.php @@ -2,6 +2,7 @@ namespace Overtrue\LaravelLike\Traits; +use Illuminate\Database\Eloquent\Casts\Attribute; use Illuminate\Database\Eloquent\Model; trait Likeable @@ -32,4 +33,11 @@ public function likers(): \Illuminate\Database\Eloquent\Relations\BelongsToMany ) ->where('likeable_type', $this->getMorphClass()); } + + protected function totalLikers(): Attribute + { + return Attribute::get(function () { + return $this->likers()->count() ?? 0; + }); + } } diff --git a/tests/FeatureTest.php b/tests/FeatureTest.php index 4368eaf..bf12ae9 100644 --- a/tests/FeatureTest.php +++ b/tests/FeatureTest.php @@ -79,8 +79,8 @@ public function test_aggregations() $user->like($book2); $this->assertSame(4, $user->likes()->count()); - $this->assertSame(4, $user->totalLikes); $this->assertSame(2, $user->likes()->withType(Book::class)->count()); + $this->assertSame(4, $user->totalLikes); } public function test_like_same_model() @@ -107,6 +107,7 @@ public function test_object_likers() $user2->like($post); $this->assertCount(2, $post->likers); + $this->assertEquals(2, $post->totalLikers); $this->assertSame('overtrue', $post->likers[0]['name']); $this->assertSame('allen', $post->likers[1]['name']);