@@ -133,6 +133,13 @@ abstract class Factory
133133 */
134134 protected static $ factoryNameResolver ;
135135
136+ /**
137+ * Whether to expand relationships by default.
138+ *
139+ * @var bool
140+ */
141+ protected static $ expandRelationshipsByDefault = true ;
142+
136143 /**
137144 * Create a new factory instance.
138145 *
@@ -144,7 +151,7 @@ abstract class Factory
144151 * @param \Illuminate\Support\Collection|null $afterCreating
145152 * @param string|null $connection
146153 * @param \Illuminate\Support\Collection|null $recycle
147- * @param bool $expandRelationships
154+ * @param bool|null $expandRelationships
148155 */
149156 public function __construct (
150157 $ count = null ,
@@ -155,7 +162,7 @@ public function __construct(
155162 ?Collection $ afterCreating = null ,
156163 $ connection = null ,
157164 ?Collection $ recycle = null ,
158- bool $ expandRelationships = true
165+ ? bool $ expandRelationships = null
159166 ) {
160167 $ this ->count = $ count ;
161168 $ this ->states = $ states ?? new Collection ;
@@ -166,7 +173,7 @@ public function __construct(
166173 $ this ->connection = $ connection ;
167174 $ this ->recycle = $ recycle ?? new Collection ;
168175 $ this ->faker = $ this ->withFaker ();
169- $ this ->expandRelationships = $ expandRelationships ;
176+ $ this ->expandRelationships = $ expandRelationships ?? self :: $ expandRelationshipsByDefault ;
170177 }
171178
172179 /**
@@ -905,6 +912,26 @@ public static function guessFactoryNamesUsing(callable $callback)
905912 static ::$ factoryNameResolver = $ callback ;
906913 }
907914
915+ /**
916+ * Specify that relationships should create parent relationships by default.
917+ *
918+ * @return void
919+ */
920+ public static function expandRelationshipsByDefault ()
921+ {
922+ static ::$ expandRelationshipsByDefault = true ;
923+ }
924+
925+ /**
926+ * Specify that relationships should not create parent relationships by default.
927+ *
928+ * @return void
929+ */
930+ public static function dontExpandRelationshipsByDefault ()
931+ {
932+ static ::$ expandRelationshipsByDefault = false ;
933+ }
934+
908935 /**
909936 * Get a new Faker instance.
910937 *
@@ -965,6 +992,7 @@ public static function flushState()
965992 static ::$ modelNameResolvers = [];
966993 static ::$ factoryNameResolver = null ;
967994 static ::$ namespace = 'Database \\Factories \\' ;
995+ static ::$ expandRelationshipsByDefault = true ;
968996 }
969997
970998 /**
0 commit comments