diff --git a/src/Builder.php b/src/Builder.php index 78e9aa33..d8365fd5 100644 --- a/src/Builder.php +++ b/src/Builder.php @@ -225,8 +225,12 @@ public function orderBy($column, $direction = 'asc') * @param string $column * @return $this */ - public function latest($column = 'created_at') + public function latest($column = null) { + if (is_null($column)) { + $column = $this->model->getCreatedAtColumn() ?? 'created_at'; + } + return $this->orderBy($column, 'desc'); } @@ -236,8 +240,12 @@ public function latest($column = 'created_at') * @param string $column * @return $this */ - public function oldest($column = 'created_at') + public function oldest($column = null) { + if (is_null($column)) { + $column = $this->model->getCreatedAtColumn() ?? 'created_at'; + } + return $this->orderBy($column, 'asc'); } diff --git a/tests/Feature/CollectionEngineTest.php b/tests/Feature/CollectionEngineTest.php index 53ed35ec..2f07a5c9 100644 --- a/tests/Feature/CollectionEngineTest.php +++ b/tests/Feature/CollectionEngineTest.php @@ -6,6 +6,7 @@ use Illuminate\Foundation\Testing\LazilyRefreshDatabase; use Laravel\Scout\Tests\Fixtures\SearchableModelWithUnloadedValue; use Laravel\Scout\Tests\Fixtures\SearchableUserModel; +use Laravel\Scout\Tests\Fixtures\SearchableUserModelWithCustomCreatedAt; use Laravel\Scout\Tests\Fixtures\SearchableUserModelWithCustomSearchableData; use Orchestra\Testbench\Concerns\WithLaravelMigrations; use Orchestra\Testbench\Concerns\WithWorkbench; @@ -142,6 +143,14 @@ public function test_it_can_order_by_latest_and_oldest() $this->assertEquals('Taylor Otwell', $models[0]->name); } + public function test_it_can_order_by_custom_model_created_at_timestamp() + { + $query = SearchableUserModelWithCustomCreatedAt::search()->latest(); + + $this->assertCount(1, $query->orders); + $this->assertEquals('created', $query->orders[0]['column']); + } + public function test_it_calls_make_searchable_using_before_searching() { Model::preventAccessingMissingAttributes(true); diff --git a/tests/Fixtures/SearchableUserModelWithCustomCreatedAt.php b/tests/Fixtures/SearchableUserModelWithCustomCreatedAt.php new file mode 100644 index 00000000..78bf3c46 --- /dev/null +++ b/tests/Fixtures/SearchableUserModelWithCustomCreatedAt.php @@ -0,0 +1,15 @@ +