/eloquent-voteable

Primary LanguagePHPMIT LicenseMIT

Eloquent Voteable

Build Status GPA Code Coverage

Installation

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

Documentation

In the code examples, $voter implements VoterInterface and $voteable implements VoteableInterface.

Voters

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;

    // ...
}

Methods

Get votes by a voter
$voter->votes;

Returns: Collection

Vote on voteable
$voter->vote($voteable, 1); // Upvote $voteable

NOTE: Vote weights must be between -127 and 127, as it is stored as a tinyInteger

Returns: Vote

Vote up a voteable
$voter->upVote($voteable);

Returns: Vote

Vote down a voteable
$voter->downVote($voteable);

Returns: Vote

Cancel a vote on a voteable
$voter->cancelVote($voteable);

Returns: null

Get the previous vote on a voteable
$voter->getVote($voteable);

Returns: Vote

Voteables

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;

    // ...
}

Methods

Get the score of a voteable
$voteable->score();

Returns: int

Get votes on a voteable
$voteable->votes;

Returns: Collection

Vote on a voteable
$voteable->voteBy($voter, 1); // Upvote $voteable

NOTE: Vote weights must be between -127 and 127, as it is stored as a tinyInteger

Returns: Vote

Vote up a voteable
$voteable->upVoteBy($voter);

Returns: Vote

Vote down a voteable
$voteable->downVoteBy($voter);

Returns: Vote

Cancel a vote on a voteable
$voteable->cancelVoteBy($voter);

Returns: null

Get the previous vote by a voter
$voteable->getVoteBy($voter);

Returns: Vote