chikeozulumba/laravel-rateable

允许多个模型使用类似五星评价系统进行评分。

2.2.1 2020-07-04 16:01 UTC

This package is not auto-updated.

Last update: 2024-09-22 08:47:44 UTC


README

Build Status Latest Stable Version License

Total Downloads Monthly Downloads Daily Downloads

为 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)。有关更多信息,请参阅 许可证文件