PHPackages                             overtrue/laravel-vote - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. overtrue/laravel-vote

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

overtrue/laravel-vote
=====================

User Vote features for Laravel Application.

4.0.0(4mo ago)12722.5k↓30.9%11[2 issues](https://github.com/overtrue/laravel-vote/issues)MITPHPPHP ^8.2CI passing

Since May 19Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/overtrue/laravel-vote)[ Packagist](https://packagist.org/packages/overtrue/laravel-vote)[ GitHub Sponsors](https://github.com/overtrue)[ RSS](/packages/overtrue-laravel-vote/feed)WikiDiscussions master Synced 2w ago

READMEChangelog (10)Dependencies (14)Versions (15)Used By (0)

Laravel Vote
------------

[](#laravel-vote)

⬆️ ⬇️ User vote system for Laravel Application.

[![CI](https://github.com/overtrue/laravel-vote/workflows/CI/badge.svg)](https://github.com/overtrue/laravel-vote/actions/workflows/ci.yml)

[![Sponsor me](https://github.com/overtrue/overtrue/raw/master/sponsor-me-button-s.svg?raw=true)](https://github.com/sponsors/overtrue)

Installing
----------

[](#installing)

```
composer require overtrue/laravel-vote -vvv
```

### Configuration &amp; Migrations

[](#configuration--migrations)

```
php artisan vendor:publish
```

then create tables:

```
php artisan migrate
```

Usage
-----

[](#usage)

### Traits

[](#traits)

#### `Overtrue\LaravelVote\Traits\Voter`

[](#overtruelaravelvotetraitsvoter)

```
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Overtrue\LaravelVote\Traits\Voter;

class User extends Authenticatable
{
    use Voter;

}
```

#### `Overtrue\LaravelVote\Traits\Voteable`

[](#overtruelaravelvotetraitsvoteable)

```
use Illuminate\Database\Eloquent\Model;
use Overtrue\LaravelVote\Traits\Votable;

class Idea extends Model
{
    use Votable;

}
```

### API

[](#api)

```
$user = User::find(1);
$idea = Idea::find(2);

$user->vote($idea, 1); // upvote
$user->vote($idea, -1); // downvote
$user->upvote($idea);
$user->downvote($idea);

// with custom number of votes
$user->upvote($idea, 3);
$user->downvote($idea, 3);

// cancel vote
$user->cancelVote($idea);

// get my voted items
$user->getVotedItems(Idea::class) // Illuminate\Database\Eloquent\Builder

// state
$user->hasVoted($idea);
$idea->hasBeenVotedBy($user);
```

#### Get model voters:

[](#get-model-voters)

```
foreach($idea->voters as $user) {
    // echo $user->name;
}
```

#### Get user voted items.

[](#get-user-voted-items)

User can easy to get Votable models to do what you want.

\*note: this method will return a `Illuminate\Database\Eloquent\Builder` \*

```
$votedItemsQuery = $user->getVotedItems();

// filter votable_type
$votedIdeasQuery = $user->getVotedItems(Idea::class);

// fetch results
$votedIdeas = $user->getVoteItems(Idea::class)->get();
$votedIdeas = $user->getVoteItems(Idea::class)->paginate();
$votedIdeas = $user->getVoteItems(Idea::class)->where('title', 'Laravel-Vote')->get();
```

### Aggregations

[](#aggregations)

### count relations

[](#count-relations)

```
// all
$user->votes()->count();

// filter votable_type
$user->votes()->ofType(Idea::class)->count();

// voters count
$idea->voters()->count();
```

List with `*_count` attribute:

```
// for Voter models:
$users = User::withCount('votes')->get();
// or
$users = User::withCount('upvotes')->get();
// or
$users = User::withCount('downvotes')->get();
// or
$users = User::withCount(['votes', 'upvotes', 'downvotes'])->get();

foreach($users as $user) {
    echo $user->votes_count;
    echo $user->upvotes_count;
    echo $user->downvotes_count;
}

// for Votable models:
$ideas = Idea::withCount('voters')->get();
// or
$ideas = Idea::withCount('upvoters')->get();
$ideas = Idea::withCount('downvoters')->get();

// or
$ideas = Idea::withCount(['voters', 'upvoters', 'downvoters'])->get();

foreach($ideas as $idea) {
    echo $idea->voters_count;
    echo $idea->upvoters_count;
    echo $idea->downvoters_count;
}
```

### Votable sum votes

[](#votable-sum-votes)

```
$user1->upvote($idea); // 1 (up)
$user2->upvote($idea); // 2 (up)
$user3->upvote($idea); // 3 (up)
$user4->downvote($idea); // -1 (down)

// sum(votes)
$idea->totalVotes(); // 2(3 - 1)

// sum(votes) where votes > 0
$idea->totalUpvotes(); // 3

// abs(sum(votes)) where votes < 0
$idea->totalDownvotes(); // 1

// appends aggregations attributes
$idea->appendsVotesAttributes();
$idea->toArray();
// result
[
    "id" => 1
    "title" => "Add socialite login support."
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"

    // these aggregations attributes will be appends.
    "total_votes" => 2
    "total_upvotes" => 3
    "total_downvotes" => 1
  ],
```

### Attach voter vote status to votable collection

[](#attach-voter-vote-status-to-votable-collection)

You can use `Voter::attachVoteStatus(Collection $votables)` to attach the voter vote status, it will set `has_voted`,`has_upvoted` and `has_downvoted` attributes to each model of `$votables`:

#### For model

[](#for-model)

```
$idea = Idea::find(1);

$user->attachVoteStatus($idea);

// result
[
    "id" => 1
    "title" => "Add socialite login support."
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_voted" => true
    "has_upvoted" => true
    "has_downvoted" => false
 ],
```

#### For `Collection | Paginator | LengthAwarePaginator | array`:

[](#for-collection--paginator--lengthawarepaginator--array)

```
$ideas = Idea::oldest('id')->get();

$user->attachVoteStatus($ideas);

$ideas = $ideas->toArray();

// result
[
  [
    "id" => 1
    "title" => "Add socialite login support."
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_voted" => true
    "has_upvoted" => true
    "has_downvoted" => false
  ],
  [
    "id" => 2
    "title" => "Add php8 support."
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_voted" => true
    "has_upvoted" => false
    "has_downvoted" => true
  ],
  [
    "id" => 3
    "title" => "Add qrcode support."
    "created_at" => "2021-05-20T03:26:16.000000Z"
    "updated_at" => "2021-05-20T03:26:16.000000Z"
    "has_voted" => false
    "has_upvoted" => false
    "has_downvoted" => false
  ],
]
```

#### For pagination

[](#for-pagination)

```
$ideas = Idea::paginate(20);

$user->attachVoteStatus($ideas->getCollection());
```

### N+1 issue

[](#n1-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
use Tests\Idea;$users = User::with('votes')->get();

foreach($users as $user) {
    $user->hasVoted($idea);
}

// Votable
$ideas = Idea::with('voters')->get();

foreach($ideas as $idea) {
    $idea->hasBeenVotedBy($user);
}

// Votable votes
$ideas = Idea::withTotalVotes() // total_votes
        ->withTotalUpvotes() // total_upvotes
        ->withTotalDownvotes() // total_downvotes
        ->get();

// same as
// withVotesAttributes() = withTotalVotes() + withTotalUpvotes() + withTotalDownvotes()
$ideas = Idea::withVotesAttributes()->get();

// result
[
  [
    "id" => 1
    "title" => "Add socialite login support."
    "created_at" => "2021-05-19T07:01:10.000000Z"
    "updated_at" => "2021-05-19T07:01:10.000000Z"
    "total_votes" => 2
    "total_upvotes" => 3
    "total_downvotes" => 1
  ],
  [
    "id" => 2
    "title" => "Add PHP8 support."
    "created_at" => "2021-05-20T07:01:10.000000Z"
    "updated_at" => "2021-05-20T07:01:10.000000Z"
    "total_votes" => 1
    "total_upvotes" => 2
    "total_downvotes" => 1
  ]
]
```

### Events

[](#events)

**Event****Description**`Overtrue\LaravelVote\Events\Voted`Triggered when the relationship is created.`Overtrue\LaravelVote\Events\VoteCancelled`Triggered when the relationship is deleted.Related packages
----------------

[](#related-packages)

- Follow: [overtrue/laravel-follow](https://github.com/overtrue/laravel-follow)
- Like: [overtrue/laravel-like](https://github.com/overtrue/laravel-like)
- Vote: [overtrue/laravel-vote](https://github.com/overtrue/laravel-Vote)
- Subscribe: [overtrue/laravel-subscribe](https://github.com/overtrue/laravel-subscribe)
- Bookmark: overtrue/laravel-bookmark (working in progress)

❤️ Sponsor me
-------------

[](#heart-sponsor-me)

[![Sponsor me](https://github.com/overtrue/overtrue/raw/master/sponsor-me.svg?raw=true)](https://github.com/sponsors/overtrue)

如果你喜欢我的项目并想支持它，[点击这里 ❤️](https://github.com/sponsors/overtrue)

Project supported by JetBrains
------------------------------

[](#project-supported-by-jetbrains)

Many thanks to Jetbrains for kindly providing a license for me to work on this and other open-source projects.

[![](https://camo.githubusercontent.com/3cf726e7cdadba47755b7f7ea4227945a92a2fa48aadf4a2573140ec6501c989/68747470733a2f2f7265736f75726365732e6a6574627261696e732e636f6d2f73746f726167652f70726f64756374732f636f6d70616e792f6272616e642f6c6f676f732f6a625f6265616d2e737667)](https://www.jetbrains.com/?from=https://github.com/overtrue)

Contributing
------------

[](#contributing)

You can contribute in one of three ways:

1. File bug reports using the [issue tracker](https://github.com/overtrue/laravel-Votes/issues).
2. Answer questions or fix bugs on the [issue tracker](https://github.com/overtrue/laravel-Votes/issues).
3. Contribute new features or update the wiki.

*The code contribution process is not very formal. You just need to make sure that you follow the PSR-0, PSR-1, and PSR-2 coding guidelines. Any new code contributions must be accompanied by unit tests where applicable.*

PHP 扩展包开发
---------

[](#php-扩展包开发)

> 想知道如何从零开始构建 PHP 扩展包？
>
> 请关注我的实战课程，我会在此课程中分享一些扩展开发经验 —— [《PHP 扩展包实战教程 - 从入门到发布》](https://learnku.com/courses/creating-package)

License
-------

[](#license)

MIT

###  Health Score

57

—

FairBetter than 98% of packages

Maintenance78

Regular maintenance activity

Popularity44

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 89.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~138 days

Recently: every ~288 days

Total

14

Last Release

126d ago

Major Versions

1.x-dev → 2.0.02021-05-21

2.x-dev → 3.0.02022-02-10

3.4.0 → 4.0.02026-04-14

### Community

Maintainers

![](https://www.gravatar.com/avatar/c507e57eab402e81335012357b7d7df6c5cafda3073adcc94b475037127d263f?d=identicon)[overtrue](/maintainers/overtrue)

---

Top Contributors

[![overtrue](https://avatars.githubusercontent.com/u/1472352?v=4)](https://github.com/overtrue "overtrue (44 commits)")[![amshehzad](https://avatars.githubusercontent.com/u/15146578?v=4)](https://github.com/amshehzad "amshehzad (1 commits)")[![aneeskhan47](https://avatars.githubusercontent.com/u/30714223?v=4)](https://github.com/aneeskhan47 "aneeskhan47 (1 commits)")[![gordanielyan](https://avatars.githubusercontent.com/u/64427318?v=4)](https://github.com/gordanielyan "gordanielyan (1 commits)")[![laravel-shift](https://avatars.githubusercontent.com/u/15991828?v=4)](https://github.com/laravel-shift "laravel-shift (1 commits)")[![sanyc](https://avatars.githubusercontent.com/u/1262624?v=4)](https://github.com/sanyc "sanyc (1 commits)")

---

Tags

laravel-voteuser-votevotevoter-vote-status

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/overtrue-laravel-vote/health.svg)

```
[![Health](https://phpackages.com/badges/overtrue-laravel-vote/health.svg)](https://phpackages.com/packages/overtrue-laravel-vote)
```

###  Alternatives

[crumbls/layup

A visual page builder plugin for Filament 5 — Divi-style grid layouts with extensible widgets.

604.0k2](/packages/crumbls-layup)[duncanmcclean/statamic-cargo

Comprehensive e-commerce addon for Statamic. Build bespoke e-commerce sites without the complexity.

3622.8k](/packages/duncanmcclean-statamic-cargo)[tomshaw/electricgrid

A feature-rich Livewire package designed for projects that require dynamic, interactive data tables.

119.8k](/packages/tomshaw-electricgrid)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
