Skip to content

Commit

Permalink
[10.x] Ordering by model's custom created_at column (#801)
Browse files Browse the repository at this point in the history
* Use Eloquent model's created at timestamp for ordering

* Add test

* Whoops, re-add test
  • Loading branch information
stevebauman authored Jan 30, 2024
1 parent 280f5b6 commit 24657f0
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
12 changes: 10 additions & 2 deletions src/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}

Expand All @@ -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');
}

Expand Down
9 changes: 9 additions & 0 deletions tests/Feature/CollectionEngineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand Down
15 changes: 15 additions & 0 deletions tests/Fixtures/SearchableUserModelWithCustomCreatedAt.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Laravel\Scout\Tests\Fixtures;

use Illuminate\Foundation\Auth\User as Model;
use Laravel\Scout\Searchable;

class SearchableUserModelWithCustomCreatedAt extends Model
{
use Searchable;

protected $table = 'users';

public const CREATED_AT = 'created';
}

0 comments on commit 24657f0

Please sign in to comment.