feat: leaderboard with top (by period) and new tabs

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Doar Mihai
2026-10-17 16:39:28 +03:00
co-authored by Claude Sonnet 5.5
parent 25e1dd2413
commit 3f8fa9f22f
7 changed files with 343 additions and 0 deletions
@@ -0,0 +1,35 @@
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class LeaderboardController extends Controller
{
private const PER_PAGE = 10;
/**
* Display the leaderboard: top products by period, or the newest products.
*/
public function index(Request $request)
{
$tab = $request->query('tab') === 'new' ? 'new' : 'top';
$period = array_key_exists((string) $request->query('period'), Product::LEADERBOARD_PERIODS)
? $request->query('period')
: 'today';
$query = Product::query()->with('tags');
$products = ($tab === 'new' ? $query->approved()->latest('products.created_at')->latest('products.id') : $query->topFor($period))
->paginate(self::PER_PAGE)
->appends($tab === 'new' ? ['tab' => 'new'] : ['tab' => 'top', 'period' => $period]);
return view('leaderboard.index', [
'products' => $products,
'tab' => $tab,
'period' => $period,
'periods' => Product::LEADERBOARD_PERIODS,
]);
}
}
+36
View File
@@ -284,6 +284,42 @@ class Product extends Model
return $query->withCount('upvotes')->orderBy('upvotes_count', 'desc');
}
/**
* Leaderboard periods: key => label.
*/
public const LEADERBOARD_PERIODS = [
'today' => 'Today',
'week' => 'This week',
'month' => 'This month',
'all' => 'All time',
];
/**
* Approved products ranked by the upvotes they received in the period,
* then by total upvotes, then newest. Products with no upvotes in the
* period are left out. Adds `period_upvotes_count` and `total_upvotes_count`.
*/
public function scopeTopFor(Builder $query, string $period): Builder
{
$since = match ($period) {
'today' => now()->startOfDay(),
'week' => now()->subDays(7),
'month' => now()->subDays(30),
default => null,
};
$inPeriod = fn (Builder $upvotes) => $since ? $upvotes->where('created_at', '>=', $since) : $upvotes;
return $query->approved()
->whereHas('upvotes', $inPeriod)
->withCount(['upvotes as period_upvotes_count' => $inPeriod])
->withCount('upvotes as total_upvotes_count')
->orderByDesc('period_upvotes_count')
->orderByDesc('total_upvotes_count')
->orderByDesc('products.created_at')
->orderByDesc('products.id');
}
/**
* Scope a query to sort products.
*/
+3
View File
@@ -2,11 +2,14 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Upvote extends Model
{
use HasFactory;
/**
* Indicates if the model should be timestamped.
*