diff --git a/src/Searcher.php b/src/Searcher.php index a31f844..f61c44a 100644 --- a/src/Searcher.php +++ b/src/Searcher.php @@ -13,9 +13,12 @@ use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; +use Illuminate\Support\Traits\Conditionable; class Searcher { + use Conditionable; + /** * Collection of models to search through. */ diff --git a/tests/SearchTest.php b/tests/SearchTest.php index 74ec743..1d84ff6 100644 --- a/tests/SearchTest.php +++ b/tests/SearchTest.php @@ -8,6 +8,7 @@ use Illuminate\Support\Collection; use ProtoneMedia\LaravelCrossEloquentSearch\OrderByRelevanceException; use ProtoneMedia\LaravelCrossEloquentSearch\Search; +use ProtoneMedia\LaravelCrossEloquentSearch\Searcher; class SearchTest extends TestCase { @@ -654,4 +655,24 @@ public function it_returns_data_consistently() { $this->assertTrue($resultA->first()->is($postA)); $this->assertTrue($resultB->first()->is($postA)); } + + /** @test */ + public function it_can_conditionally_apply_ordering() + { + Carbon::setTestNow(now()); + $postA = Post::create(['title' => 'foo']); + + Carbon::setTestNow(now()->subDay()); + $postB = Post::create(['title' => 'foo2']); + + $results = Search::add(Post::class, 'title') + ->when(true, fn (Searcher $searcher) => $searcher->orderByDesc()) + ->get('foo'); + + $this->assertInstanceOf(Collection::class, $results); + $this->assertCount(2, $results); + + $this->assertTrue($results->first()->is($postA)); + $this->assertTrue($results->last()->is($postB)); + } }