Feature: Adding Sorting To Product List
This commit is contained in:
@@ -22,12 +22,16 @@ class ProductService
|
||||
/**
|
||||
* @return array{data: array<int, array>, meta: array}
|
||||
*/
|
||||
public function list(?ProductFilters $filters = null, int $perPage = 24, int $page = 1): array
|
||||
public function list(?ProductFilters $filters = null, int $perPage = 24, int $page = 1, ?ProductSort $sort = null): array
|
||||
{
|
||||
$options = ['filter' => $this->buildFilter($filters)];
|
||||
|
||||
if ($sort !== null) {
|
||||
$options['sort'] = [$sort->toMeilisearchSort()];
|
||||
}
|
||||
|
||||
$paginator = Product::search('')
|
||||
->options([
|
||||
'filter' => $this->buildFilter($filters),
|
||||
])
|
||||
->options($options)
|
||||
->paginateRaw(perPage: $perPage, page: $page);
|
||||
|
||||
return [
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Catalog;
|
||||
|
||||
/**
|
||||
* Sort options for ProductService::list(), each mapped to a Meilisearch `sort`
|
||||
* clause against a field indexed as sortable by Modules\Core\Search\ProductIndexer
|
||||
* (see its getSortableFields()). Adding a case here requires the matching field
|
||||
* to also be sortable in the index, re-synced via `php artisan lunar:meilisearch:setup`.
|
||||
*/
|
||||
enum ProductSort: string
|
||||
{
|
||||
case PriceAsc = 'price_asc';
|
||||
case PriceDesc = 'price_desc';
|
||||
case Newest = 'newest';
|
||||
|
||||
public function toMeilisearchSort(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::PriceAsc => 'price:asc',
|
||||
self::PriceDesc => 'price:desc',
|
||||
self::Newest => 'created_at:desc',
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user