Skip to content

Commit

Permalink
Fix factory breaking when trying to determine whether a relation is e…
Browse files Browse the repository at this point in the history
…mpty (#45135)
  • Loading branch information
axlon committed Nov 29, 2022
1 parent defd920 commit 10a51e6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Eloquent/Factories/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Enumerable;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\ForwardsCalls;
Expand Down Expand Up @@ -329,7 +330,7 @@ protected function store(Collection $results)
$model->save();

foreach ($model->getRelations() as $name => $items) {
if ($items->isEmpty()) {
if ($items instanceof Enumerable && $items->isEmpty()) {
$model->unsetRelation($name);
}
}
Expand Down
18 changes: 18 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,24 @@ public function test_belongs_to_many_relationship_related_models_set_on_instance
$this->assertCount(1, $role->users);
}

public function test_relation_can_be_loaded_before_model_is_created()
{
$user = FactoryTestUserFactory::new(['name' => 'Taylor Otwell'])->createOne();

$post = FactoryTestPostFactory::new()
->for($user, 'user')
->afterMaking(function (FactoryTestPost $post) {
$post->load('user');
})
->createOne();

$this->assertTrue($post->relationLoaded('user'));
$this->assertTrue($post->user->is($user));

$this->assertCount(1, FactoryTestUser::all());
$this->assertCount(1, FactoryTestPost::all());
}

public function test_belongs_to_many_relationship_with_existing_model_instances()
{
$roles = FactoryTestRoleFactory::times(3)
Expand Down

0 comments on commit 10a51e6

Please sign in to comment.