Install the package using composer
composer require natzim/eloquent-voteable
Add the service provider to the providers
array in config/app.php
'providers' => [
// ...
Natzim\EloquentVoteable\VoteableServiceProvider::class
]
Publish the migrations
php artisan vendor:publish
Run the migrations
php artsain migrate
In the code examples, $voter
implements VoterInterface
and $voteable
implements VoteableInterface
.
Voters are any model that can vote on voteables.
Voter models should implement VoterInterface
and use Votes
:
use Natzim\EloquentVoteable\Contracts\VoterInterface;
use Natzim\EloquentVoteable\Traits\Votes;
class User extends Model implements VoterInterface
{
use Votes;
// ...
}
$voter->votes;
Returns: Collection
$voter->vote($voteable, 1); // Upvote $voteable
NOTE: Vote weights must be between -127 and 127, as it is stored as a tinyInteger
Returns: Vote
$voter->upVote($voteable);
Returns: Vote
$voter->downVote($voteable);
Returns: Vote
$voter->cancelVote($voteable);
Returns: null
$voter->getVote($voteable);
Returns: Vote
Voteables are any model that can be voted on by voters.
Voteable classes should implement VoteableInterface
and use Voteable
:
use Natzim\EloquentVoteable\Contracts\VoteableInterface;
use Natzim\EloquentVoteable\Traits\Voteable;
class Post extends Model implements VoteableInterface
{
use Voteable;
// ...
}
$voteable->score();
Returns: int
$voteable->votes;
Returns: Collection
$voteable->voteBy($voter, 1); // Upvote $voteable
NOTE: Vote weights must be between -127 and 127, as it is stored as a tinyInteger
Returns: Vote
$voteable->upVoteBy($voter);
Returns: Vote
$voteable->downVoteBy($voter);
Returns: Vote
$voteable->cancelVoteBy($voter);
Returns: null
$voteable->getVoteBy($voter);
Returns: Vote