imagina / laravel-rateable
允许使用类似五星级系统对多个模型进行评分。
Requires
- php: >=7.2
- illuminate/database: ^6.0|^7.0|^8.0
- illuminate/support: ^6.0|^7.0|^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- orchestra/testbench: ^5.0
- phpunit/phpunit: ^9.0
- psalm/plugin-laravel: ^1.2
- vimeo/psalm: ^3.11
README
为 Laravel 6/7 提供一个特性,允许对应用程序中的任何 Eloquent 模型进行评分。
评分可以是五星级风格,也可以是简单的 +1/-1 风格。
兼容性
Laravel 版本 < 6.x 应使用 1.x 版本。2.x 版本可能与最新的 Laravel 5.x 版本至少暂时兼容,但任何新开发都将明确关注 Laravel 6.x+ 兼容性,并可能发生破坏性更改,因此不建议使用 Laravel 版本 < 6.x 安装 2.x 版本,这样做存在风险。
安装
您可以通过 composer 安装此软件包。
composer require willvincent/laravel-rateable
您可以使用以下命令发布和运行迁移:
php artisan vendor:publish --provider="willvincent\Rateable\RateableServiceProvider" --tag="migrations" php artisan migrate
与大多数 Laravel 软件包一样,如果您使用的是 Laravel 5.5 或更高版本,该软件包将自动发现(如果您对此不熟悉,请了解更多)。
如果您使用的是 Laravel 5.5 之前的版本,您需要注册 Rateable 服务提供者。在您的 config/app.php
文件中,将 'willvincent\Rateable\RateableServiceProvider'
添加到 $providers
数组的末尾。
'providers' => [ Illuminate\Foundation\Providers\ArtisanServiceProvider::class, Illuminate\Auth\AuthServiceProvider::class, ... willvincent\Rateable\RateableServiceProvider::class, ],
用法
为了将模型标记为“可评分”,导入 Rateable
特性。
<?php namespace App; use willvincent\Rateable\Rateable; use Illuminate\Database\Eloquent\Model; class Post extends Model { use Rateable; }
现在,您的模型可以访问一些额外的函数。
首先,向您的模型添加评分
$post = Post::first(); // Add a rating of 5, from the currently authenticated user $post->rate(5); dd(Post::first()->ratings);
或者,您可能想要强制用户只能对每个模型进行一次评分,并且如果他们提交新值,它将 更新 他们现有的评分。
在这种情况下,您将想要使用 rateOnce()
代替
$post = Post::first(); // Add a rating of 3, or change the user's existing rating _to_ 3. $post->rateOnce(3); dd(Post::first()->ratings);
一旦模型有一些评分,您可以获取平均评分
$post = Post::first(); dd($post->averageRating); // $post->averageRating() also works for this.
您还可以获取评分百分比。这也是如何强制最大评分值的方法。
$post = Post::first(); dd($post->ratingPercent(10)); // Ten star rating system // Note: The value passed in is treated as the maximum allowed value. // This defaults to 5 so it can be called without passing a value as well. // $post->ratingPercent(5) -- Five star rating system totally equivilent to: // $post->ratingPercent()
您还可以获取给定可评分项目的评分总和或平均值,对于当前(授权)已投票/评分的用户。
$post = Post::first(); // These values depend on the user being logged in, // they use the Auth facade to fetch the current user's id. dd($post->userAverageRating); dd($post->userSumRating);
想知道一个模型有多少评分吗?
dd($post->timesRated()); // Or if you specifically want the number of unique users that have rated the model: dd($post->usersRated());
测试
composer test
变更日志
请参阅 CHANGELOG 了解最近更改的更多信息。
贡献
请参阅 CONTRIBUTING 了解详细信息。
鸣谢
许可证
MIT 许可证 (MIT)。请参阅 许可证文件 了解更多信息。