Using Eloquent::firstOrCreate() to prevent duplicate seeding

Submitted by chadwithuhc - 4 years ago

Inside my seeders I often use this trick to prevent from re-seeding already present values. For example, if you are creating a base seed of production data -- say a pre-defined list of values -- and add a new item but do not want to delete all seed data and re-seed, you can try this. Note that, there are some flaws to it. Such as: It will not delete missing values if your new list has changed, or if you set the attributes too specific, you may end up creating a duplicate (for instance, if you have the same item with different `order` values due to rearranging in the list).

// Let's take a list and assume we've seeded this data once...
$relationship = array(
    'Mother',
    'Father',
    'Sibling'
);

// And now we want to add to the list, two new options
$relationship = array(
    'Mother',
    'Father',
    'Sibling',
    'Grandparent',
    'Pet'
);

// In our seeder if we do
foreach ($relationship as $name) {
    RelationshipValues::firstOrCreate([
        'name' => $name
    ]);
}

// Our new values will match what we have in our updated list.
// It will return the prior entry for existing values
// Or create a new one for non-existent
comments powered by Disqus