Laravel Factory With Unique Value Columns

Submitted by lcdss - 1 year ago

When you have a model with unique value column and tries seeder your table using a big amout, sometimes the QueryException is thrown, because Faker doesn't know what values was previously generated and the number of combinations is limited.

// database/factories/ModelFactory.php

$factory->define(App\Subject::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->city,
    ];
});

// database/seeds/SubjectTableSeeder.php

<?php

use Illuminate\Database\Seeder;

class SubjectTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $subjects = factory(App\Subject::class, 500)->make();

        foreach ($subjects as $subject) {
            repeat:
            try {
                $subject->save();
            } catch (\Illuminate\Database\QueryException $e) {
                $subject = factory(App\Subject::class)->make();
                goto repeat;
            }
        }
    }
}

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks