Laravel foreign key constraint table truncate

In Laravel whenever a table has a foreign key constraint set then truncating in seed class would raise an sql violation error.

The solution is to simply disable foreign key check for truncating the tables and enable it after seeding
Suppose We have a RoleAndUserSeeder as

truncate();
        DB::table('roles')->truncate();
        DB::table('users')->truncate();
        $role = Role::create([
            'name' => 'Admin',
            'slug' => 'admin',  // MUST USE admin, DO NOT CHANGE!
            'description' => 'The one who manage the site',
            'created_at' => new \Carbon\Carbon(),
            'updated_at' => new \Carbon\Carbon(),
        ]);

        $user = User::create([
            'name' => 'Usman Akram',
            'email' => '***@***.com',
            'password' => '12345678',
            'created_at' => new \Carbon\Carbon(),
            'updated_at' => new \Carbon\Carbon(),
        ]);
        
        $user->roles()->attach($role);
        
        
    }
}

then in database seeder class you can write as

call(UserTableSeeder::class);
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
        Eloquent::reguard();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *