diff --git a/src/Concerns/SortsQuery.php b/src/Concerns/SortsQuery.php index c61d216f..e96e5a6c 100644 --- a/src/Concerns/SortsQuery.php +++ b/src/Concerns/SortsQuery.php @@ -69,7 +69,12 @@ protected function addRequestedSortsToQuery(): void $sort = $this->findSort($key); - $sort?->sort($this, $descending); + if (! $sort) { + // Apply default sort if no valid sorts are present in the request + $this->defaultSorts($this->allowedSorts->toArray()); + } else { + $sort->sort($this, $descending); + } }); } diff --git a/tests/SortTest.php b/tests/SortTest.php index 95534beb..caa6f22e 100644 --- a/tests/SortTest.php +++ b/tests/SortTest.php @@ -430,6 +430,21 @@ public function __invoke(Builder $query, bool $descending, string $property): Bu $this->assertSortedDescending($sortedModels, 'name'); }); +// Test for issue resolution +it('applies default sort when all provided sort parameters are invalid', function () { + $request = new Request([ + 'sort' => 'invalid_column', + ]); + + $sortedModels = QueryBuilder::for(TestModel::class, $request) + ->allowedSorts('name') + ->defaultSort('-name') + ->get(); + + // The default sort '-name' should be applied, resulting in models being sorted by 'name' in descending order. + $this->assertSortedDescending($sortedModels, 'name'); +}); + // Helpers function createQueryFromSortRequest(?string $sort = null): QueryBuilder {