03
NovCjmellor/rating is a Laravel package that allows for ratings to be added to a Model
Imagine you have a Recipes Model and want your users to rate your culinary delights. This package allows you to achieve this.
You can install the package via composer:
composer require cjmellor/rating
You can publish and run the migrations with the following:
php artisan vendor:publish --tag="rating-migrations"
php artisan migrate
You can publish the config file with:
php artisan vendor:publish --tag="rating-config"
To rate a Model, you must add the CanBeRated trait to the Model in question.
use Cjmellor\Rating\Concerns\CanBeRated;
class Recipe extends Model
{
use CanBeRated;
// ...
}
Now you can rate this Model:
$recipe = Recipe::find(1);
$recipe->rate(score: 2);
You can view how many ratings a particular Model has:
$recipe->ratings;
// this will return a Collection
You can get an overall percentage of the amount of Users’ who have rated a Model:
Imagine you want a five-star rating system, and you have a Model that has been rated a 3 and a 5 by two Users’
$recipe->ratingPercent(maxLength: 5);
// 80.0
This will equate to 80%. A float is returned. Changing the maxLength will recalculate the percentage.
The package comes with a bunch of Attributes that you can use. The results of these are based on a single Model rated by two Users’ with 3 and 5 ratings.
$recipe->averageRating; // "4.0000"
$recipe->averageRatingByUser; // "5.0000"
$recipe->averageSumOfUser; // 5
$recipe->ratedByUsers; // 2
$recipe->ratedInTotal; // 2
$recipe->sumRating; // "8"
The package comes with an optional blade component for displaying the Models’ ratings.
You must publish the file to get access to it
php artisan vendor:publish --tag="rating-component"
You can now use the new component:
<x-show-rating score="80.0" />
The component has customizable attributes:
public string $color = 'text-yellow-400',
public string $family = 'FontAwesome',
public $innerStars = '\f005 \f005 \f005 \f005 \f005',
public $outerStars = '\f006 \f006 \f006 \f006 \f006',
public float $score = 0.0,
public string $textSize = 'text-2xl',
For more details about this package, Please visit Github.
Published at : 03-11-2022
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.
Launch project