cjmellor/rating

Laravel 包,允许为模型添加评分

v2.2.0 2024-03-03 20:45 UTC

This package is auto-updated.

Last update: 2024-09-08 17:01:06 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads Packagist PHP Version Laravel Version Livewire Version

想象你有一个菜谱模型,并且希望用户对你的烹饪佳肴进行评分。这个包允许你实现这一点。

示例

CanBeRated 特性添加到你想进行评分的模型。

use Cjmellor\Rating\Concerns\CanBeRated;

class Recipe extends Model
{
    use CanBeRated;
    
    // ...
}

现在你可以对任何模型进行评分。

$recipe = Recipe::find(1);

$recipe->rate(4);

安装

您可以通过 composer 安装此包

composer require cjmellor/rating

您可以使用以下命令发布和运行迁移

php artisan vendor:publish --tag="rating-migrations"
php artisan migrate

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="rating-config"

这是发布配置文件的内容

return [
    'users' => [
        'table' => 'users',
        'primary_key' => 'user_id',
    ],

    'max_rating' => 5,
    
    'undo_rating' => true,
];

使用方法

要对模型进行评分,你必须将 CanBeRated 特性添加到相关的模型中。

use Cjmellor\Rating\Concerns\CanBeRated;

class Recipe extends Model
{
    use CanBeRated;
    
    // ...
}

评分模型

$recipe = Recipe::find(1);

$recipe->rate(score: 2);

查看模型的评分

$recipe->ratings;

你可以得到一个模型评分的用户总数百分比

假设你有一个五星级评分系统,并且有一个被两个用户分别评为 35 的模型

$recipe->ratingPercent(maxLength: 5);

// 80.0

这将等于 80%。返回一个浮点数。更改 maxLength 将重新计算百分比。

然后你可以使用这个百分比作为组件的 score 属性。

注意

默认情况下,maxLength 由配置选项确定。你可以通过传递一个值来覆盖它。

取消评分模型

默认情况下,您可以取消评分模型。如果您不希望用户取消评分模型,请将 undo_rating 配置选项设置为 true。

要取消评分模型,您可以使用 unrate 方法

$recipe->unrate();

此包附带一些属性,您可以使用。 以下结果基于单个模型由两个用户分别评分为 3 5

$recipe->averageRating; // "4.0000"
$recipe->averageRatingByUser; // "5.0000"
$recipe->averageSumOfUser; // 5
$recipe->ratedByUsers; // 2
$recipe->ratedInTotal; // 2
$recipe->sumRating; // "8" 

Livewire 组件

要查看评分的实际效果,您可以使用 Livewire 组件。这允许您在前端静态显示评分,并允许用户通过点击星星对模型进行评分。

警告

您必须安装 Tailwind CSS 和 Font Awesome,尽管 Font Awesome 可以替换为您自己的首选图标集

使用组件

<livewire:rating size="text-7xl" score="55" :model="$recipe" />

组件具有可定制的属性,包括

public string $iconBgColor = 'text-yellow-300';
public string $iconFgColor = 'text-yellow-400';
public string $iconBg = 'far fa-star';
public string $iconFg = 'fas fa-star';
public float $score = 0;
public string $size = 'text-base';
public bool $static = false;

如果您将取消评分模型的配置设置为 true,则将显示一个图标,允许您取消评分模型。

测试

composer test

变更日志

有关最近更改的更多信息,请参阅 CHANGELOG

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件