Skip to content
Advertisement

laravel seeds unique column ignore duplicate entries

i have a Seeder in Laravel

public function run()
    {
        $user = AppAdmin::create([

            'first_name'     => 'first',
            'last_name'    => 'last',
            'phone'    => '',
            'email'    => 'mail@gmail.com',
        ]);
    }

in this email is unique,

php artisan db:seed

when I run first time its entering records into the database, when I run again its showing duplicate entry.

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'mail@gmail.com' for key 'email'

do i have option to ignore that.?

Advertisement

Answer

We have an option to check whether the given email exists in the table or not.

public function run(){
            $admin = DB::table('admins')->where('email', '=', 'mail@gmail.com')->first();

            if ($admin === null) {
                // user doesn't exist
                $user = AppAdmin::create([

                    'first_name'     => 'Walter',
                    'last_name'    => 'Brown',
                    'phone'    => '',
                    'email'    => 'admin@gmail.com',
                    'password' => Hash::make('Admin123'),
                    'is_active'    => 1,
                    'remember_token' => str_random(10)
                ]);
             }
        }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement