#batch insert factory

24 messages ยท Page 1 of 1 (latest)

strong jolt
#

Hi! I'd like to batch my inserts with a factory, like this example I found on github:

User::insert(
    User::factory()->count(100)->make()->toArray();
);

but that would not fire HasUuid events to fill out the uuid column on the model I am inserting into, is there a way to do both? or do I have to manually generate the UUIDs myself and insert them this way?..

Thank you!

topaz flame
#

Batch why?

#

Just use create. If you want to speed it up, stick your create in a DB transaction so all records being inserted only use one transaction.

#
DB::transaction(function () {
    User::factory()->count(1000)->create();
});
strong jolt
topaz flame
#

Transactions in seeding can make a world of difference. The only thing you can't speed up is seeding password hashes if you aren't using a pre-made hash.

strong jolt
topaz flame
#

Factories are for seeding and feature tests. I'd avoid using them to make production models, not their intent.

#

Eloquent fires all events as normal when you new up a model, fill, and save. Update. Or Model::create()

strong jolt
#

so what did I use last time that didnt fire the uuid stuff?

topaz flame
#

Used make. That's the same as new Model();

#

No events are fired yet

#

Create fires events which triggers the uuid listener

strong jolt
#

make was later I think I was just regularly inserting and it didnt do the uuid stuff, but I remember what docs page I was on to verify, give me a moment

#

ahh I was doing:

#
DB::table('users')->insert([
#

which bypasses eloquent

#

if I was users creating

#

it'd fire?

topaz flame
#

Yea you bypassed eloquent entirely

strong jolt
#

makes sense

topaz flame
#

Using the pure Db query builder has its places, but know you'll get no eloquent niceties

strong jolt
#

the transaction also worked exactly the way I wanted, thanks!