search and filtering

This commit is contained in:
Doar Mihai
2026-02-07 14:36:33 +02:00
parent 7a99c3eb59
commit 89be4d4329
10 changed files with 1506 additions and 23 deletions
+70
View File
@@ -139,6 +139,76 @@ class Product extends Model
return $query->where('status', $status);
}
/**
* Scope a query to search products by title and description.
*/
public function scopeSearch(Builder $query, ?string $search): Builder
{
if (empty($search)) {
return $query;
}
return $query->where(function ($subQuery) use ($search) {
$subQuery->where('title', 'like', '%' . $search . '%')
->orWhere('description', 'like', '%' . $search . '%');
});
}
/**
* Scope a query to filter by category.
*/
public function scopeByCategory(Builder $query, ?int $categoryId): Builder
{
if (empty($categoryId)) {
return $query;
}
return $query->where('category_id', $categoryId);
}
/**
* Scope a query to filter by date range.
*/
public function scopeDateRange(Builder $query, ?string $range): Builder
{
if (empty($range)) {
return $query;
}
return match($range) {
'today' => $query->whereDate('created_at', today()),
'week' => $query->where('created_at', '>=', now()->subWeek()),
'month' => $query->where('created_at', '>=', now()->subMonth()),
'year' => $query->where('created_at', '>=', now()->subYear()),
default => $query,
};
}
/**
* Scope a query to sort products by popularity (upvotes count).
*/
public function scopePopular(Builder $query): Builder
{
return $query->withCount('upvotes')->orderBy('upvotes_count', 'desc');
}
/**
* Scope a query to sort products.
*/
public function scopeSortBy(Builder $query, ?string $sort): Builder
{
if (empty($sort)) {
return $query->latest();
}
return match($sort) {
'popular' => $query->withCount('upvotes')->orderBy('upvotes_count', 'desc'),
'oldest' => $query->oldest(),
'newest' => $query->latest(),
default => $query->latest(),
};
}
/**
* Get the product's thumbnail URL.
*/