Sling Academy
Home/PHP/Laravel + Eloquent: How to Build a Rating System

Laravel + Eloquent: How to Build a Rating System

Last updated: January 26, 2024

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.

Next Article: How to Serve Static Files in Laravel

Previous Article: How to handle JSON POST request in Laravel

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array