diff --git a/src/SortableTrait.php b/src/SortableTrait.php index b400f88..4b77ac1 100644 --- a/src/SortableTrait.php +++ b/src/SortableTrait.php @@ -4,6 +4,7 @@ use ArrayAccess; use Illuminate\Database\Eloquent\Builder; +use Illuminate\Database\Eloquent\SoftDeletingScope; use InvalidArgumentException; trait SortableTrait @@ -69,7 +70,9 @@ public static function setNewOrder($ids, int $startOrder = 1) $primaryKeyColumn = $model->getKeyName(); foreach ($ids as $id) { - static::where($primaryKeyColumn, $id)->update([$orderColumnName => $startOrder++]); + static::withoutGlobalScope(SoftDeletingScope::class) + ->where($primaryKeyColumn, $id) + ->update([$orderColumnName => $startOrder++]); } } diff --git a/tests/DummyWithSoftDeletes.php b/tests/DummyWithSoftDeletes.php new file mode 100644 index 0000000..7c28150 --- /dev/null +++ b/tests/DummyWithSoftDeletes.php @@ -0,0 +1,17 @@ +assertEquals(Dummy::all()->count(), (new Dummy())->getHighestOrderNumber()); } + /** @test */ + public function it_can_get_the_highest_order_number_with_trashed_models() + { + $this->setUpSoftDeletes(); + + DummyWithSoftDeletes::first()->delete(); + + $this->assertEquals(DummyWithSoftDeletes::withTrashed()->count(), (new DummyWithSoftDeletes())->getHighestOrderNumber()); + } + /** @test */ public function it_can_set_a_new_order() { @@ -44,6 +54,40 @@ public function it_can_set_a_new_order_from_collection() } } + /** @test */ + public function it_can_set_a_new_order_with_trashed_models() + { + $this->setUpSoftDeletes(); + + $dummies = DummyWithSoftDeletes::all(); + + $dummies->random()->delete(); + + $newOrder = Collection::make($dummies->pluck('id'))->shuffle(); + + DummyWithSoftDeletes::setNewOrder($newOrder); + + foreach (DummyWithSoftDeletes::withTrashed()->orderBy('order_column')->get() as $i => $dummy) { + $this->assertEquals($newOrder[$i], $dummy->id); + } + } + + /** @test */ + public function it_can_set_a_new_order_without_trashed_models() + { + $this->setUpSoftDeletes(); + + DummyWithSoftDeletes::first()->delete(); + + $newOrder = Collection::make(DummyWithSoftDeletes::pluck('id'))->shuffle(); + + DummyWithSoftDeletes::setNewOrder($newOrder); + + foreach (DummyWithSoftDeletes::orderBy('order_column')->get() as $i => $dummy) { + $this->assertEquals($newOrder[$i], $dummy->id); + } + } + /** @test */ public function it_will_determine_to_sort_when_creating_if_sortable_attribute_does_not_exist() { diff --git a/tests/TestCase.php b/tests/TestCase.php index c8fba3f..aefbe86 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -51,4 +51,11 @@ protected function setUpDatabase() Dummy::create(['name' => $i]); }); } + + protected function setUpSoftDeletes() + { + $this->app['db']->connection()->getSchemaBuilder()->table('dummies', function (Blueprint $table) { + $table->softDeletes(); + }); + } }