Laravel + Eloquent: How to Build a Rating System

Updated: January 26, 2024 By: Guest Contributor Post a comment

Introduction

This tutorial shows how to build a robust rating system within a Laravel application using Eloquent ORM. A rating system is an essential feature for many web applications to collect user feedback. Laravel, a prominent PHP web application framework, coupled with its elegant Eloquent ORM, makes implementing such a system straightforward.

Defining the Rating Model

First, create a Rating model and migration. Run the Artisan command:

php artisan make:model Rating -m

Add the necessary columns in the created migration file:

Schema::create('ratings', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id');
    $table->foreignId('post_id');
    $table->tinyInteger('rating');
    $table->timestamps();
});

Run the migration:

php artisan migrate

Establishing Relationships

For this example, suppose we have a ‘Post’ model where users can leave ratings. Add the relationship in the Rating model:

public function post()
{
    return $this->belongsTo(Post::class);
}

Also, append the inverse relationship in the Post model:

public function ratings()
{
    return $this->hasMany(Rating::class);
}

Creating a Rating Controller

Create a new controller using Artisan:

php artisan make:controller RatingController

Add store and update methods:

public function store(Request $request)
{
    // Validation and storage logic
}

public function update(Rating $rating, Request $request)
{
    // Update logic
}

Blade Templates and Forms

Design your rating component in a Blade template:

<form method="POST" action="{{ route('ratings.store') }}">
    @csrf
    <div>
        // Rating input elements
    </div>
    <button type="submit">Submit Rating</button>
</form>

Create a similar update form using PUT method:

<form method="POST" action="{{ route('ratings.update', $rating) }}">
    @csrf
    @method('PUT')
    // Rating input elements for updating
</form>

Handling Rating Logic in the Controller

In the store method, validate and save the rating:

$request->validate(['rating' => 'required|integer|between:1,5']);
$rating = new Rating($request->all());
// Attach user ID to the rating
$rating->user_id = auth()->id();
$rating->save();
return back()->with('message', 'Rating submitted successfully!');

In the update method, re-use the validation logic and update:

$request->validate(['rating' => 'required|integer|between:1,5']);
$rating->update($request->all());
return back()->with('message', 'Rating updated successfully!');

Calculating Aggregate Ratings

To compute average ratings in the Post model:

public function averageRating()
{
    return $this->ratings()->average('rating');
}

Display the average rate in Blade templates:

<p>Average Rating: {{ number_format($post->averageRating(), 1) }}</p>

Closing Thoughts

While simple, this tutorial covers establishing a basic rating system in Laravel using Eloquent ORM. Further sophistication may involve AJAX for a seamless user experience, validation against multiple submissions, and more complex user-interface elements such as star ratings. However, with this foundation, there are plenty of opportunities to expand and customize to fit any specific application requirements.