Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add lazy method in eloquent factory #34923

Merged
merged 2 commits into from
Oct 21, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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