Skip to content

Commit 10a51e6

Browse files
authored
Fix factory breaking when trying to determine whether a relation is empty (#45135)
1 parent defd920 commit 10a51e6

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/Illuminate/Database/Eloquent/Factories/Factory.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
use Illuminate\Database\Eloquent\SoftDeletes;
1212
use Illuminate\Support\Carbon;
1313
use Illuminate\Support\Collection;
14+
use Illuminate\Support\Enumerable;
1415
use Illuminate\Support\Str;
1516
use Illuminate\Support\Traits\Conditionable;
1617
use Illuminate\Support\Traits\ForwardsCalls;
@@ -329,7 +330,7 @@ protected function store(Collection $results)
329330
$model->save();
330331

331332
foreach ($model->getRelations() as $name => $items) {
332-
if ($items->isEmpty()) {
333+
if ($items instanceof Enumerable && $items->isEmpty()) {
333334
$model->unsetRelation($name);
334335
}
335336
}

tests/Database/DatabaseEloquentFactoryTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,24 @@ public function test_belongs_to_many_relationship_related_models_set_on_instance
364364
$this->assertCount(1, $role->users);
365365
}
366366

367+
public function test_relation_can_be_loaded_before_model_is_created()
368+
{
369+
$user = FactoryTestUserFactory::new(['name' => 'Taylor Otwell'])->createOne();
370+
371+
$post = FactoryTestPostFactory::new()
372+
->for($user, 'user')
373+
->afterMaking(function (FactoryTestPost $post) {
374+
$post->load('user');
375+
})
376+
->createOne();
377+
378+
$this->assertTrue($post->relationLoaded('user'));
379+
$this->assertTrue($post->user->is($user));
380+
381+
$this->assertCount(1, FactoryTestUser::all());
382+
$this->assertCount(1, FactoryTestPost::all());
383+
}
384+
367385
public function test_belongs_to_many_relationship_with_existing_model_instances()
368386
{
369387
$roles = FactoryTestRoleFactory::times(3)

0 commit comments

Comments
 (0)