Add rating system in your laravel app

You can now add rating system in your laravel app very easily by using a laravel package called rating which is maintained by ghanem . this package will help you alot if you are planning to add rating system in your website or app so lets get started with installation

Installation is very easy using composer

First, pull in the package through Composer.

composer require ghanem/rating

And then include the service provider within app/config/app.php.

'providers' => [
    GhanemRatingRatingServiceProvider::class
];

At last you need to publish and run the migration.

php artisan vendor:publish --provider="GhanemRatingRatingServiceProvider" && php artisan migrate



you can Setup a Model using trait below

<?php

namespace App;

use GhanemRatingContractsRating;
use GhanemRatingTraitsRating as RatingTrait;
use IlluminateDatabaseEloquentModel;

class Post extends Model implements Rating
{
    use RatingTrait;
}

this is the method of creating rating

$user = User::first();
$post = Post::first();

$rating = $post->rating([
    'title' => 'Some title',
    'body' => 'Some body',
    'rating' => 5,
], $user);

dd($rating);

Update a rating

$rating = $post->updateRating(1, [
    'title' => 'new title',
    'body' => 'new body',
    'rating' => 3,
]);

you can delete a rating  as shown below

$post->deleteRating(1);

fetch the average rating:

$post->averageRating()

fetch the rating percentage.

This is also how you enforce a maximum rating value.

$post->ratingPercent()

$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.



 

About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

  • Ankit Dimri

    very good artical

Pin It on Pinterest

Shares

Get the best in web dev

Join dunebook.com and recieve best in web dev , once a week FREE

An email has been Sent to your Inbox ! Please Confirm your Subscription :)