PHP code example of ghanem / rating

1. Go to this page and download the library: Download ghanem/rating library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ghanem / rating example snippets


use Ghanem\Rating\Traits\Ratingable;

class Post extends Model
{
    use Ratingable;
}

use Ghanem\Rating\Traits\CanRate;

class User extends Model
{
    use CanRate;
}

// From the ratable model
$rating = $post->rating(['rating' => 5], $user);

// From the author model
$rating = $user->rate($post, ['rating' => 5]);

$rating = $post->ratingUnique(['rating' => 5], $user);

// Or from the author
$rating = $user->rateUnique($post, ['rating' => 5]);

$rating = $post->updateRating($ratingId, ['rating' => 3]);

$post->deleteRating($ratingId);

$post->rating([
    'rating' => 5,
    'body' => 'Great article!',
], $user);

$restaurant->rating(['rating' => 5, 'type' => 'food'], $user);
$restaurant->rating(['rating' => 3, 'type' => 'service'], $user);

$restaurant->avgRating('food');    // 5.0
$restaurant->avgRating('service'); // 3.0
$restaurant->avgRating();          // 4.0 (all types)

$post->rating(['rating' => 5, 'weight' => 2], $verifiedUser);
$post->rating(['rating' => 3, 'weight' => 1], $regularUser);

$post->weightedAvgRating(); // 4.33

$post->avgRating()          // average rating
$post->sumRating()          // sum of all ratings
$post->countRatings()       // total count
$post->countPositive()      // count where rating > 0
$post->countNegative()      // count where rating < 0
$post->ratingPercent()      // percentage (default max: 5)
$post->ratingPercent(10)    // percentage with custom max
$post->weightedAvgRating()  // weighted average

$post->avgRating
$post->sumRating
$post->countRatings
$post->countPositive
$post->countNegative
$post->ratingPercent
$post->weightedAvgRating

$user->hasRated($post);          // bool
$user->getRating($post);         // Rating|null
$user->averageGivenRating();     // float
$user->totalGivenRatings();      // int
$user->ratings;                  // all ratings given

$post->isRatedBy($user);            // bool
$post->isRatedBy($user, 'food');    // bool (scoped)

// Eager load rating aggregates
Post::withAvgRating()->get();
Post::withSumRating()->get();
Post::withCountRatings()->get();

// Order by ratings
Post::orderByAvgRating()->get();        // desc by default
Post::orderByAvgRating('asc')->get();
Post::orderBySumRating()->get();
Post::orderByCountRatings()->get();

// Filter by minimum rating
Post::minAvgRating(3.5)->get();
Post::minSumRating(10)->get();

// Scoped by type
Post::withAvgRating('food')->get();
Post::orderByAvgRating('desc', 'food')->get();

// routes/web.php
Route::post('posts/{post}/rate', [RatingController::class, 'store'])
    ->middleware('auth')
    ->name('posts.rate');

class RatingController extends Controller
{
    public function store(Request $request, Post $post)
    {
        $data = $request->validate([
            'rating' => [' $request->user()->rateUnique($post, $data);

        return back()->with('status', 'Thanks for rating!');
    }
}

$posts = Post::withAvgRating()->withCountRatings()->paginate();

return [
    'min' => 1,
    'max' => 5,
    'allow_negative' => false,
];
bash
php artisan vendor:publish --provider="Ghanem\Rating\RatingServiceProvider"
php artisan migrate
bash
php artisan vendor:publish --tag=rating-config
blade
<form method="POST" action="{{ route('posts.rate', $post) }}">
    @csrf

    <fieldset class="rating-input">
        <legend>Your rating</legend>

        @foreach (range(5, 1) as $value)
            <input
                type="radio"
                id="star-{{ $value }}"
                name="rating"
                value="{{ $value }}"
                {{ auth()->user()?->getRating($post)?->rating == $value ? 'checked' : '' }}
            >
            <label for="star-{{ $value }}" title="{{ $value }} stars">★</label>
        @endforeach
    </fieldset>

    <textarea name="body" placeholder="Leave a review (optional)"></textarea>

    <button type="submit">Submit</button>
</form>