diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index f6f90b544391..acede7c91308 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -1061,22 +1061,27 @@ protected function insertAndSetId(Builder $query, $attributes) */ public static function destroy($ids) { - // We'll initialize a count here so we will return the total number of deletes - // for the operation. The developers can then check this number as a boolean - // type value or get this total count of records deleted for logging, etc. - $count = 0; - if ($ids instanceof BaseCollection) { $ids = $ids->all(); } $ids = is_array($ids) ? $ids : func_get_args(); + // Avoid a no-op database query by bailing early + if (count($ids) === 0) { + return 0; + } + // We will actually pull the models from the database table and call delete on // each of them individually so that their events get fired properly with a // correct set of attributes in case the developers wants to check these. $key = ($instance = new static)->getKeyName(); + // We'll initialize a count here so we will return the total number of deletes + // for the operation. The developers can then check this number as a boolean + // type value or get this total count of records deleted for logging, etc. + $count = 0; + foreach ($instance->whereIn($key, $ids)->get() as $model) { if ($model->delete()) { $count++; diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 2d3f3e10ebdf..114c4ae6f5c2 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -293,6 +293,17 @@ public function testDestroyMethodCallsQueryBuilderCorrectlyWithCollection() EloquentModelDestroyStub::destroy(new Collection([1, 2, 3])); } + public function testDestroyMethodCallsQueryBuilderCorrectlyWithMultipleArgs() + { + EloquentModelDestroyStub::destroy(1, 2, 3); + } + + public function testDestroyMethodCallsQueryBuilderCorrectlyWithEmptyIds() + { + $count = EloquentModelEmptyDestroyStub::destroy([]); + $this->assertSame(0, $count); + } + public function testWithMethodCallsQueryBuilderCorrectly() { $result = EloquentModelWithStub::with('foo', 'bar'); @@ -2400,6 +2411,17 @@ public function newQuery() } } +class EloquentModelEmptyDestroyStub extends Model +{ + public function newQuery() + { + $mock = m::mock(Builder::class); + $mock->shouldReceive('whereIn')->never(); + + return $mock; + } +} + class EloquentModelHydrateRawStub extends Model { public static function hydrate(array $items, $connection = null)