🎉 This package helps you to add user based vote system to your model.
You can install the package using Composer:
$ composer require "jcc/laravel-vote:~2.0"
Then add the service provider to config/app.php
:
Jcc\LaravelVote\VoteServiceProvider::class
Publish the migrations file:
$ php artisan vendor:publish --provider="Jcc\LaravelVote\VoteServiceProvider" --tag="migrations"
Finally, use VoteTrait in User model:
use Jcc\LaravelVote\Traits\Voter;
class User extends Model
{
use Voter;
}
Or use CanBeVoted in Comment model:
use Jcc\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 |
---|---|
Jcc\LaravelVote\Events\Voted |
Triggered when the relationship is created or updated. |
Jcc\LaravelVote\Events\CancelVoted |
Triggered when the relationship is deleted. |