diff --git a/src/Illuminate/Database/Eloquent/Factories/Factory.php b/src/Illuminate/Database/Eloquent/Factories/Factory.php index 0210fa4293b1..191e8d3d11f2 100644 --- a/src/Illuminate/Database/Eloquent/Factories/Factory.php +++ b/src/Illuminate/Database/Eloquent/Factories/Factory.php @@ -471,7 +471,7 @@ protected function expandAttributes(array $definition) return collect($definition) ->map($evaluateRelations = function ($attribute) { if ($attribute instanceof self) { - $attribute = $this->getRandomRecycledModel($attribute->modelName()) + $attribute = $this->getRandomRecycledModel($attribute->modelName())?->getKey() ?? $attribute->recycle($this->recycle)->create()->getKey(); } elseif ($attribute instanceof Model) { $attribute = $attribute->getKey(); diff --git a/tests/Database/DatabaseEloquentFactoryTest.php b/tests/Database/DatabaseEloquentFactoryTest.php index c35017eb6133..b46051ac0272 100644 --- a/tests/Database/DatabaseEloquentFactoryTest.php +++ b/tests/Database/DatabaseEloquentFactoryTest.php @@ -898,7 +898,7 @@ public function definition() return [ 'commentable_id' => FactoryTestPostFactory::new(), 'commentable_type' => FactoryTestPost::class, - 'user_id' => FactoryTestUserFactory::new(), + 'user_id' => fn () => FactoryTestUserFactory::new(), 'body' => $this->faker->name(), ]; }