Likes and Ratings System Implementation for Website

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Likes and Ratings System Implementation

Likes and ratings are user reactions to content. Like — binary reaction, rating — scale (1–5 stars). Technical tasks: atomicity with concurrent requests, prevent duplication, cache counter.

Database Structure

-- Universal likes table (polymorphic)
CREATE TABLE likes (
    id            SERIAL PRIMARY KEY,
    user_id       INTEGER  NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    likeable_id   INTEGER  NOT NULL,
    likeable_type VARCHAR(50) NOT NULL,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (user_id, likeable_id, likeable_type)
);

CREATE INDEX ON likes(likeable_type, likeable_id);

-- Ratings
CREATE TABLE ratings (
    id            SERIAL PRIMARY KEY,
    user_id       INTEGER  NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    ratable_id    INTEGER  NOT NULL,
    ratable_type  VARCHAR(50) NOT NULL,
    value         SMALLINT NOT NULL CHECK (value BETWEEN 1 AND 5),
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    UNIQUE (user_id, ratable_id, ratable_type)
);

-- Counters in main tables (denormalization)
ALTER TABLE articles ADD COLUMN likes_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE products ADD COLUMN rating_avg NUMERIC(3,2) NOT NULL DEFAULT 0;
ALTER TABLE products ADD COLUMN ratings_count INTEGER NOT NULL DEFAULT 0;

Laravel: Likes

trait Likeable
{
    public function likes(): MorphMany
    {
        return $this->morphMany(Like::class, 'likeable');
    }

    public function isLikedBy(?User $user): bool
    {
        if (!$user) return false;
        return Cache::remember(
            "liked:{$this->getMorphClass()}:{$this->id}:{$user->id}",
            300,
            fn() => $this->likes()->where('user_id', $user->id)->exists()
        );
    }
}

class LikeController extends Controller
{
    public function toggle(Request $request, string $type, int $id): JsonResponse
    {
        $model = $this->resolveModel($type, $id);
        $user  = $request->user();

        $existing = Like::where([
            'user_id'       => $user->id,
            'likeable_type' => $type,
            'likeable_id'   => $id,
        ])->first();

        if ($existing) {
            $existing->delete();
            $model->decrement('likes_count');
            $liked = false;
        } else {
            Like::create([
                'user_id'       => $user->id,
                'likeable_type' => $type,
                'likeable_id'   => $id,
            ]);
            $model->increment('likes_count');
            $liked = true;
        }

        Cache::forget("liked:{$type}:{$id}:{$user->id}");

        return response()->json([
            'liked' => $liked,
            'count' => $model->fresh()->likes_count,
        ]);
    }
}

Ratings (Stars)

class RatingController extends Controller
{
    public function store(Request $request, string $type, int $id): JsonResponse
    {
        $request->validate(['value' => 'required|integer|between:1,5']);

        $model = $this->resolveModel($type, $id);

        Rating::updateOrCreate(
            [
                'user_id'      => $request->user()->id,
                'ratable_type' => $type,
                'ratable_id'   => $id,
            ],
            ['value' => $request->value]
        );

        $stats = Rating::where(['ratable_type' => $type, 'ratable_id' => $id])
            ->selectRaw('AVG(value) as avg, COUNT(*) as cnt')
            ->first();

        $model->update([
            'rating_avg'    => round($stats->avg, 2),
            'ratings_count' => $stats->cnt,
        ]);

        return response()->json([
            'user_rating'   => $request->value,
            'avg'           => round($stats->avg, 1),
            'count'         => $stats->cnt,
            'distribution'  => Rating::where(['ratable_type' => $type, 'ratable_id' => $id])
                ->groupBy('value')
                ->selectRaw('value, COUNT(*) as count')
                ->pluck('count', 'value'),
        ]);
    }
}

React: UI Components

function LikeButton({ type, id, initialCount, initialLiked }: LikeButtonProps) {
  const [liked, setLiked] = useState(initialLiked);
  const [count, setCount] = useState(initialCount);
  const [loading, setLoading] = useState(false);

  const toggle = async () => {
    if (loading) return;
    setLoading(true);

    setLiked(!liked);
    setCount(c => liked ? c - 1 : c + 1);

    try {
      const { data } = await api.post(`/api/likes/${type}/${id}/toggle`);
      setLiked(data.liked);
      setCount(data.count);
    } catch {
      setLiked(liked);
      setCount(count);
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      onClick={toggle}
      className={`like-btn ${liked ? 'like-btn--active' : ''}`}
      aria-label={liked ? 'Unlike' : 'Like'}
      aria-pressed={liked}
    >
      <HeartIcon filled={liked} />
      <span>{count.toLocaleString('en-US')}</span>
    </button>
  );
}

function StarRating({ type, id, userRating, avgRating, ratingsCount }: StarRatingProps) {
  const [hover, setHover] = useState(0);
  const [selected, setSelected] = useState(userRating || 0);

  const handleRate = async (value: number) => {
    setSelected(value);
    await api.post(`/api/ratings/${type}/${id}`, { value });
  };

  return (
    <div className="star-rating">
      <div className="stars" role="radiogroup" aria-label="Rating">
        {[1, 2, 3, 4, 5].map(star => (
          <button
            key={star}
            role="radio"
            aria-checked={selected === star}
            aria-label={`${star} stars`}
            className={`star ${star <= (hover || selected) ? 'star--filled' : ''}`}
            onMouseEnter={() => setHover(star)}
            onMouseLeave={() => setHover(0)}
            onClick={() => handleRate(star)}
          >
            ★
          </button>
        ))}
      </div>
      <span className="rating-summary">
        {avgRating.toFixed(1)} ({ratingsCount.toLocaleString('en-US')} ratings)
      </span>
    </div>
  );
}

Implementation Timeline

Likes system (polymorphic) with React UI and optimistic updates: 2–3 days. 1–5 star ratings with aggregates: +1–2 days.