centrex/laravel-ratings

为Laravel中的任何模型添加评分

v1.2.0 2024-07-02 09:13 UTC

This package is auto-updated.

Last update: 2024-09-08 16:40:57 UTC


README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

这里应该放置你的描述。限制为一两段话。考虑添加一个小的示例。

目录

安装

您可以通过composer安装此包

composer require centrex/ratings

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

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

这是已发布配置文件的内容

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

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

使用

InterectsWithRating特质添加到您想要进行评分的模型中。

use Centrex\Ratings\Concerns\InterectsWithRating;

class Product extends Model
{
    use InterectsWithRating;
    
    // ...
}

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

评分模型

$product = Product::find(1);
$product->rate(4);

$product->rate(score: 2);

查看模型的评分

$product->ratings;

您可以获得对模型评分的用户总数的整体百分比

假设您想要一个五星评分系统,并且有两个用户对一个模型分别进行了35的评分

$product->ratingPercent(maxLength: 5);

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

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

注意

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

取消评分模型

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

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

$product->unrate();

该包附带了许多您可以使用属性。 这些结果基于单个模型被两个用户分别评分3 5

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

Livewire组件

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

警告

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

使用组件

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

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

public string $iconBgColor = 'text-yellow-300';
public string $iconFgColor = 'text-yellow-400';
public float $score = 0;
public string $size = 'text-base';
public bool $static = false;

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

测试

🧹 使用 Pint 保持现代代码库

composer lint

✅ 使用 Rector 运行重构

composer refacto

⚗️ 使用 PHPStan 运行静态分析

composer test:types

✅ 使用 PEST 运行单元测试

composer test:unit

🚀 运行整个测试套件

composer test

更新日志

请参阅更新日志以获取有关最近更改的更多信息。

贡献

请参阅贡献以获取详细信息。

致谢

许可证

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