Skip to content

Commit 81423ea

Browse files
committed
Add the lazy method to delay the creation of models in the database when using model factories
1 parent 7c283c2 commit 81423ea

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

src/Illuminate/Database/Eloquent/FactoryBuilder.php

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,13 @@ class FactoryBuilder
3636
*/
3737
protected $states;
3838

39+
/**
40+
* The lazy status delays the creation of the models in the database.
41+
*
42+
* @var bool
43+
*/
44+
protected $lazy = false;
45+
3946
/**
4047
* The states to apply.
4148
*
@@ -102,6 +109,19 @@ public function states($states)
102109
return $this;
103110
}
104111

112+
/**
113+
* Set the lazy status.
114+
*
115+
* @param bool $value
116+
* @return $this
117+
*/
118+
public function lazy($value = true)
119+
{
120+
$this->lazy = $value;
121+
122+
return $this;
123+
}
124+
105125
/**
106126
* Create a collection of models and persist them to the database.
107127
*
@@ -112,13 +132,17 @@ public function create(array $attributes = [])
112132
{
113133
$results = $this->make($attributes);
114134

115-
if ($results instanceof Model) {
116-
$results->save();
117-
} else {
118-
$results->each->save();
119-
}
135+
$callback = function () use ($results) {
136+
if ($results instanceof Model) {
137+
$results->save();
138+
} else {
139+
$results->each->save();
140+
}
141+
142+
return $results;
143+
};
120144

121-
return $results;
145+
return $this->lazy ? $callback : $callback();
122146
}
123147

124148
/**

0 commit comments

Comments
 (0)