The package helps you to add user based vote system to your model
jimchen/laravel-vote is a Laravel package for the package helps you to add user based vote system to your model.
It currently has 1 GitHub stars and 807 downloads on Packagist (latest version v1.0.0).
Install it with composer require jimchen/laravel-vote.
Discover more Laravel packages by jimchen
or browse all Laravel packages to compare alternatives.
Last updated
:tada: This package helps you to add user based vote system to your model.
fork from jcc/laravel-vote
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;
}
$comment = Comment::find(1);
$user->upVote($comment);
$comment = Comment::find(1);
$user->downVote($comment);
$comment = Comment::find(1);
$user->cancelVote($comment);
$user->getVotedItems(Comment::class)->get();
$comment = Comment::find(1);
$user->hasVoted($comment);
$comment = Comment::find(1);
$user->hasUpVoted($comment);
$comment = Comment::find(1);
$user->hasDownVoted($comment);
$comment->voters()->get();
$comment->voters()->count();
$comment->upVoters()->get();
$comment->upVoters()->count();
$comment->downVoters()->get();
$comment->downVoters()->count();
$user = User::find(1);
$comment->isVotedBy($user);
$user = User::find(1);
$comment->isUpVotedBy($user);
$user = User::find(1);
$comment->isDownVotedBy($user);
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);
}
| Event | Description |
| --- | --- |
| JimChen\LaravelVote\Events\Voted | Triggered when the relationship is created or updated. |
| JimChen\LaravelVote\Events\CancelVoted | Triggered when the relationship is deleted. |