diff --git a/src/Illuminate/Database/Eloquent/Concerns/PreventsCircularRecursion.php b/src/Illuminate/Database/Eloquent/Concerns/PreventsCircularRecursion.php index 8c06c5351579..67d1007a05ec 100644 --- a/src/Illuminate/Database/Eloquent/Concerns/PreventsCircularRecursion.php +++ b/src/Illuminate/Database/Eloquent/Concerns/PreventsCircularRecursion.php @@ -44,7 +44,7 @@ protected static function getRecursiveCallStack($object): array * @param mixed $default * @return mixed */ - protected function once($callback, $default = null) + protected function withoutRecursion($callback, $default = null) { $trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 2); @@ -53,13 +53,12 @@ protected function once($callback, $default = null) $object = $onceable->object ?? $this; $stack = static::getRecursiveCallStack($object); - if (isset($stack[$onceable->hash])) { + if (array_key_exists($onceable->hash, $stack)) { return $stack[$onceable->hash]; } try { - // Set the default first to prevent recursion - $stack[$onceable->hash] = $default; + $stack[$onceable->hash] = is_callable($default) ? call_user_func($default) : $default; static::getRecursionCache()->offsetSet($object, $stack); return call_user_func($onceable->callable); diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index 5ad8f7a3ce2f..69a8a3b07fe8 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -1084,7 +1084,7 @@ protected function decrementQuietly($column, $amount = 1, array $extra = []) */ public function push() { - return $this->once(function () { + return $this->withoutRecursion(function () { if (! $this->save()) { return false; } @@ -1647,9 +1647,9 @@ public function callNamedScope($scope, array $parameters = []) */ public function toArray() { - return $this->once( + return $this->withoutRecursion( fn () => array_merge($this->attributesToArray(), $this->relationsToArray()), - $this->attributesToArray(), + fn () => $this->attributesToArray(), ); } @@ -1997,7 +1997,7 @@ public function getQueueableId() */ public function getQueueableRelations() { - return $this->once(function () { + return $this->withoutRecursion(function () { $relations = []; foreach ($this->getRelations() as $key => $relation) { diff --git a/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php b/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php index 3c3cc8fa46df..057c4375422b 100644 --- a/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php +++ b/tests/Database/DatabaseConcernsPreventsCircularRecursionTest.php @@ -137,7 +137,7 @@ public function __construct( public function callStack(): int { - return $this->once( + return $this->withoutRecursion( function () { static::$globalStack++; $this->instanceStack++; @@ -150,7 +150,7 @@ function () { public function callOtherStack(): int { - return $this->once( + return $this->withoutRecursion( function () { $this->other->callStack();