willvincent / laravel-rateable
允许多个模型使用类似五星级评分系统进行评分。
3.3.0
2024-05-03 05:42 UTC
Requires
- php: ^8.0
- illuminate/database: ^8.53 || ^9.0|^10.0 || ^11.0
- illuminate/support: ^8.0 || ^9.0|^10.0 || ^11.0
Requires (Dev)
- orchestra/testbench: ^6.23 || ^7.0|^8.0 || ^9.0
- phpunit/phpunit: ^9.5 || ^10.5
README
为Laravel 6/7/8/9提供特性,允许您的应用程序中的任何Eloquent模型进行评分。
评分可以是五星级风格,也可以是简单的+1/-1风格。
兼容性
Laravel版本小于6.x应使用1.x版本
Laravel版本大于等于6.x且小于8.x应使用2.x+版本
Laravel版本大于等于8.x应使用3.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
更新日志
请参阅更新日志以获取有关最近更改的更多信息。
贡献
请参阅贡献以获取详细信息。
致谢
许可协议
MIT许可(MIT)。请参阅许可文件以获取更多信息。