Skip to content

Commit 7b3911f

Browse files
authored
Add config to disable InvalidSortQuery exception (#830)
* Add config to disable InvalidSortQuery exception * $sort can be null
1 parent 44eaa38 commit 7b3911f

File tree

3 files changed

+20
-1
lines changed

3 files changed

+20
-1
lines changed

config/query-builder.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@
3232
*/
3333
'disable_invalid_filter_query_exception' => false,
3434

35+
/*
36+
* By default the package will throw an `InvalidSortQuery` exception when a sort in the
37+
* URL is not allowed in the `allowedSorts()` method.
38+
*/
39+
'disable_invalid_sort_query_exception' => false,
40+
3541
/*
3642
* By default the package inspects query string of request using $request->query().
3743
* You can change this behavior to inspect the request body using $request->input()

src/Concerns/SortsQuery.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ protected function addRequestedSortsToQuery()
8585

8686
$sort = $this->findSort($key);
8787

88-
$sort->sort($this, $descending);
88+
$sort?->sort($this, $descending);
8989
});
9090
}
9191

@@ -99,6 +99,10 @@ protected function findSort(string $property): ?AllowedSort
9999

100100
protected function ensureAllSortsExist(): void
101101
{
102+
if (config('query-builder.disable_invalid_sort_query_exception')) {
103+
return;
104+
}
105+
102106
$requestedSortNames = $this->request->sorts()->map(function (string $sort) {
103107
return ltrim($sort, '-');
104108
});

tests/SortTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,15 @@
136136
->allowedSorts('id');
137137
});
138138

139+
it('does not throw invalid sort query exception when disable in config', function () {
140+
config(['query-builder.disable_invalid_sort_query_exception' => true]);
141+
142+
createQueryFromSortRequest('name')
143+
->allowedSorts('id');
144+
145+
expect(true)->toBeTrue();
146+
});
147+
139148
test('an invalid sort query exception contains the unknown and allowed sorts', function () {
140149
$exception = InvalidSortQuery::sortsNotAllowed(collect(['unknown sort']), collect(['allowed sort']));
141150

0 commit comments

Comments
 (0)