Skip to content

Commit e6c54e4

Browse files
authored
[12.x] Fix Factory@insert() to allow for array casts (#57794)
* use attributesToArray * fix hidden
1 parent 8fb8706 commit e6c54e4

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

src/Illuminate/Database/Eloquent/Factories/Factory.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,10 @@ public function insert(array $attributes = [], ?Model $parent = null): void
471471
$query = $model->newQueryWithoutScopes();
472472

473473
$query->fillAndInsert(
474-
$madeCollection->map(fn (Model $model) => $model->getAttributes())->all()
474+
$madeCollection->withoutAppends()
475+
->setHidden([])
476+
->map(static fn (Model $model) => $model->attributesToArray())
477+
->all()
475478
);
476479
}
477480

tests/Database/DatabaseEloquentFactoryTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1012,6 +1012,18 @@ public function test_factory_can_insert_with_hidden()
10121012
$this->assertEquals('abc', $userModel->options);
10131013
}
10141014

1015+
public function test_factory_can_insert_with_array_casts()
1016+
{
1017+
(new FactoryTestUserWithArrayFactory())->count(2)->insert();
1018+
$users = DB::table('users')->get();
1019+
foreach($users as $user) {
1020+
$this->assertEquals(['rtj'], json_decode($user->options, true));
1021+
$createdAt = Carbon::parse($user->created_at);
1022+
$updatedAt = Carbon::parse($user->updated_at);
1023+
$this->assertEquals($updatedAt, $createdAt);
1024+
}
1025+
}
1026+
10151027
/**
10161028
* Get a database connection instance.
10171029
*
@@ -1234,6 +1246,28 @@ class FactoryTestUseFactoryAttribute extends Eloquent
12341246
use HasFactory;
12351247
}
12361248

1249+
class FactoryTestUserWithArray extends Eloquent
1250+
{
1251+
protected $table = 'users';
1252+
protected function casts()
1253+
{
1254+
return ['options' => 'array'];
1255+
}
1256+
}
1257+
1258+
class FactoryTestUserWithArrayFactory extends Factory
1259+
{
1260+
protected $model = FactoryTestUserWithArray::class;
1261+
public function definition()
1262+
{
1263+
return [
1264+
'name' => 'killer mike',
1265+
'options' => ['rtj'],
1266+
];
1267+
}
1268+
}
1269+
1270+
12371271
enum Name: string
12381272
{
12391273
case Taylor = 'totwell';

0 commit comments

Comments
 (0)