lucasbrito-wdt/laravel-rateable

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

dev-main 2023-06-25 19:00 UTC

This package is auto-updated.

Last update: 2024-09-25 21:50:37 UTC


README

Latest Stable Version License

Total Downloads Monthly Downloads Daily Downloads

为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 lucasbrito-wdt/laravel-rateable

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

php artisan vendor:publish --provider="lucasbrito-wdt\Rateable\RateableServiceProvider" --tag="migrations"
php artisan migrate

与大多数Laravel包一样,如果您使用的是Laravel 5.5或更高版本,则该包将被自动发现(如果您对此不熟悉,请了解更多)。

如果您使用的是Laravel 5.5之前的版本,则需要注册Rateable 服务提供者。在您的 config/app.php 文件中,将 'lucasbrito-wdt\Rateable\RateableServiceProvider' 添加到 $providers 数组的末尾。

'providers' => [

    Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    ...
    lucasbrito-wdt\Rateable\RateableServiceProvider::class,

],

使用方法

为了将模型标记为“可评分”,导入 Rateable 特质。

<?php namespace App;

use lucasbrito-wdt\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(10, 5); -- Ref, Rate
$post->rate(10, 5, 'Comentário'); -- Ref, Rate, Comment
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)。有关更多信息,请参阅许可文件