jimchen / laravel-vote
The package helps you to add user based vote system to your model
v1.0.0
2021-05-20 03:26 UTC
Requires
- php: >=7.2
- laravel/framework: ^5.5|~6.0|~7.0|~8.0
- symfony/polyfill-php80: ^1.22
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.18
- mockery/mockery: ^1.3
- orchestra/testbench: ^3.5|~4.0|~5.0|~6.0
- phpstan/phpstan: ^0.12.81
This package is auto-updated.
Last update: 2024-09-21 08:37:07 UTC
README
🎉 This package helps you to add user based vote system to your model.
fork from jcc/laravel-vote
Installation
You can install the package using Composer:
$ composer require "jimchen/laravel-vote"
Then add the service provider to config/app.php
:
JimChen\LaravelVote\VoteServiceProvider::class
Publish the migrations file:
$ php artisan vendor:publish --provider="JimChen\LaravelVote\VoteServiceProvider" --tag="migrations"
Finally, use VoteTrait in User model:
use JimChen\LaravelVote\Traits\Voter; class User extends Model { use Voter; }
Or use CanBeVoted in Comment model:
use JimChen\LaravelVote\Traits\Votable; class Comment extends Model { use Votable; }
Usage
For User model
Up vote a comment or comments
$comment = Comment::find(1); $user->upVote($comment);
Down vote a comment or comments
$comment = Comment::find(1); $user->downVote($comment);
Cancel vote a comment or comments
$comment = Comment::find(1); $user->cancelVote($comment);
Get user has voted comment items
$user->getVotedItems(Comment::class)->get();
Check if user has up or down vote
$comment = Comment::find(1); $user->hasVoted($comment);
Check if user has up vote
$comment = Comment::find(1); $user->hasUpVoted($comment);
Check if user has down vote
$comment = Comment::find(1); $user->hasDownVoted($comment);
For Comment model
Get comment voters
$comment->voters()->get();
Count comment voters
$comment->voters()->count();
Get comment up voters
$comment->upVoters()->get();
Count comment up voters
$comment->upVoters()->count();
Get comment down voters
$comment->downVoters()->get();
Count comment down voters
$comment->downVoters()->count();
Check if voted by
$user = User::find(1); $comment->isVotedBy($user);
Check if up voted by
$user = User::find(1); $comment->isUpVotedBy($user);
Check if down voted by
$user = User::find(1); $comment->isDownVotedBy($user);
N+1 issue
To avoid the N+1 issue, you can use eager loading to reduce this operation to just 2 queries. When querying, you may specify which relationships should be eager loaded using the with
method:
// Voter $users = User::with('votes')->get(); foreach($users as $user) { $user->hasVoted($comment); } // Votable $comments = Comment::with('voters')->get(); foreach($comments as $comment) { $comment->isVotedBy($user); }