Skip to content

Commit 24657f0

Browse files
authored
[10.x] Ordering by model's custom created_at column (#801)
* Use Eloquent model's created at timestamp for ordering * Add test * Whoops, re-add test
1 parent 280f5b6 commit 24657f0

3 files changed

Lines changed: 34 additions & 2 deletions

File tree

src/Builder.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,12 @@ public function orderBy($column, $direction = 'asc')
225225
* @param string $column
226226
* @return $this
227227
*/
228-
public function latest($column = 'created_at')
228+
public function latest($column = null)
229229
{
230+
if (is_null($column)) {
231+
$column = $this->model->getCreatedAtColumn() ?? 'created_at';
232+
}
233+
230234
return $this->orderBy($column, 'desc');
231235
}
232236

@@ -236,8 +240,12 @@ public function latest($column = 'created_at')
236240
* @param string $column
237241
* @return $this
238242
*/
239-
public function oldest($column = 'created_at')
243+
public function oldest($column = null)
240244
{
245+
if (is_null($column)) {
246+
$column = $this->model->getCreatedAtColumn() ?? 'created_at';
247+
}
248+
241249
return $this->orderBy($column, 'asc');
242250
}
243251

tests/Feature/CollectionEngineTest.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
77
use Laravel\Scout\Tests\Fixtures\SearchableModelWithUnloadedValue;
88
use Laravel\Scout\Tests\Fixtures\SearchableUserModel;
9+
use Laravel\Scout\Tests\Fixtures\SearchableUserModelWithCustomCreatedAt;
910
use Laravel\Scout\Tests\Fixtures\SearchableUserModelWithCustomSearchableData;
1011
use Orchestra\Testbench\Concerns\WithLaravelMigrations;
1112
use Orchestra\Testbench\Concerns\WithWorkbench;
@@ -142,6 +143,14 @@ public function test_it_can_order_by_latest_and_oldest()
142143
$this->assertEquals('Taylor Otwell', $models[0]->name);
143144
}
144145

146+
public function test_it_can_order_by_custom_model_created_at_timestamp()
147+
{
148+
$query = SearchableUserModelWithCustomCreatedAt::search()->latest();
149+
150+
$this->assertCount(1, $query->orders);
151+
$this->assertEquals('created', $query->orders[0]['column']);
152+
}
153+
145154
public function test_it_calls_make_searchable_using_before_searching()
146155
{
147156
Model::preventAccessingMissingAttributes(true);
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
namespace Laravel\Scout\Tests\Fixtures;
4+
5+
use Illuminate\Foundation\Auth\User as Model;
6+
use Laravel\Scout\Searchable;
7+
8+
class SearchableUserModelWithCustomCreatedAt extends Model
9+
{
10+
use Searchable;
11+
12+
protected $table = 'users';
13+
14+
public const CREATED_AT = 'created';
15+
}

0 commit comments

Comments
 (0)