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

PiousVenom's avatar

Seeder inheritance

I'm not sure if what I'm thinking is feasible or even a good way to do things, but thought I'd ask.

I've got a a seeder called PromoCodeSeeder. Right now, I can add new promo codes to it and it works, but it would go through every promo code that I've added before, and thus take exponentially more amount of time to process as time goes on. So what I'm thinking is to extend it and create a new seeder for each promo code, and thus only have to call the newest ones. Is this a good idea? Or is there a better method of doing this? My goal is to have something we can do at deploy time that is automagically run so we wouldn't have to worry if we "forgot" it.

0 likes
1 reply
martinbean's avatar

@piousvenom I think the phrase you may be looking for is “idempotent seeder”, where you can re-run the seeder as many times as you like and it’ll only update database records once.

If you’re trying to seed a database table with predefined promo codes then you could just have a seeder that simply tries to insert each promo code and ignores if it exists already:

class PromoCodeSeeder extends Seeder
{
    protected array $codes = [
        'BLACKFRIDAY2024',
        'CHRISTMAS2024',
        'BOXINGDAY2024',
    ];

    public function run(): void
    {
        foreach ($this->codes as $code) {
            PromoCode::query()->insertOrIgnore([
                'code' => $code,
            ]);
        }
    }
}

This will let you run php artisan db:seed --class=PromoCodeSeeder as many times as you want, and only missing promo codes will be inserted. Any attempts to insert existing promo codes (that raise duplicate record errors) will then be silently discarded (although other errors will still be raised as normal).

You could also go one step further and have promo codes be read from an environment variable, or a CSV file that’s Git-ignored, so that updating promo codes doesn’t require a code change and deployment.

1 like

Please or to participate in this conversation.