diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index 31ebd20d4f23..2365fbb34805 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -295,6 +295,10 @@ public function chunk($count, callable $callback) */ public function each(callable $callback, $count = 1000) { + if (is_null($this->getOrderBys())) { + $this->orderBy($this->model->getQualifiedKeyName(), 'asc'); + } + return $this->chunk($count, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($item, $key) === false) { diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index 4ffd1f5d9e41..c3f6d6ffacfe 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -3,6 +3,7 @@ namespace Illuminate\Database\Query; use Closure; +use RuntimeException; use BadMethodCallException; use Illuminate\Support\Arr; use Illuminate\Support\Str; @@ -1572,9 +1573,15 @@ public function chunk($count, callable $callback) * @param callable $callback * @param int $count * @return bool + * + * @throws \RuntimeException */ public function each(callable $callback, $count = 1000) { + if (is_null($this->getOrderBys())) { + throw new RuntimeException('You must provided an ordering on the query.'); + } + return $this->chunk($count, function ($results) use ($callback) { foreach ($results as $key => $value) { if ($callback($item, $key) === false) { @@ -1584,6 +1591,18 @@ public function each(callable $callback, $count = 1000) }); } + /** + * Returns the currently set ordering. + * + * @return array|null + */ + public function getOrderBys() + { + $property = $this->unions ? 'unionOrders' : 'orders'; + + return $this->{$property}; + } + /** * Get an array with the values of a given column. *