Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

martinszeltins's avatar

How to insert multiple rows using factory create?

If I have a pre-defined array of values that I would like to insert into the database with one query (instead of looping over them and running n queries), is this possible?

For example:

$names = ['john', 'bob', 'martin', 'eric', 'joe', 'chris'];

foreach($names as $name) {
    Name::factory()->create([
        'name' => $name,
    ]);
}

Not too bad for 6 names but if I had defined 6000 names long array, then that would result in 6000 queries... yikes...

0 likes
5 replies
Tray2's avatar

You can do this to create five names.

Name::factory()->count(5)->create();
martinszeltins's avatar

@tray2 but I want to use my pre-defined array and create the names - john, bob, martin etc.

Tray2's avatar

Then you have to loop over them. Or create a call for each name.

However factories should be used to create test data. If you are seeding the database you should use seeders instead.

https://laravel.com/docs/8.x/seeding

1 like
dzalev's avatar

You can insert array in database with one query like this:

$prepared = collect($names['data'])->map(function($item) use ($timestamp) {
            $item['created_at'] = $timestamp;
            $item['updated_at'] = $timestamp;
            return $item;
        });

        Name::insert($prepared->toArray());

but as Tray2 suggested, factories should be used to create test data.

1 like

Please or to participate in this conversation.