Skip to content

Commit

Permalink
[8.x] Add lazy method in eloquent factory (#34923)
Browse files Browse the repository at this point in the history
* Add lazy method in eloquent factory

* Update Factory.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
mathieutu and taylorotwell committed Oct 21, 2020
1 parent cac1e0d commit 49c2374
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Illuminate/Database/Eloquent/Factories/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,20 @@ public function create($attributes = [], ?Model $parent = null)
return $results;
}

/**
* Create a callback that persists a model in the database when invoked.
*
* @param array $attributes
* @param \Illuminate\Database\Eloquent\Model|null $parent
* @return \Closure
*/
public function lazy(array $attributes = [], ?Model $parent = null)
{
return function () use ($attributes, $parent) {
return $this->create($attributes, $parent);
};
}

/**
* Set the connection name on the results and store them.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Database/DatabaseEloquentFactoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,20 @@ public function test_expanded_model_attributes_can_be_created()
$this->assertSame('Test Title', $post['title']);
}

public function test_lazy_model_attributes_can_be_created()
{
$userFunction = FactoryTestUserFactory::new()->lazy();
$this->assertIsCallable($userFunction);
$this->assertInstanceOf(Eloquent::class, $userFunction());

$userFunction = FactoryTestUserFactory::new()->lazy(['name' => 'Taylor Otwell']);
$this->assertIsCallable($userFunction);

$user = $userFunction();
$this->assertInstanceOf(Eloquent::class, $user);
$this->assertSame('Taylor Otwell', $user->name);
}

public function test_multiple_model_attributes_can_be_created()
{
$posts = FactoryTestPostFactory::new()->times(10)->raw();
Expand Down

0 comments on commit 49c2374

Please sign in to comment.