How to Truncate a Table With a Foreign Key Reference While Seeding?

2015-05-13 Laravel

If you work with migrations in your Laravel application, sooner or later you may see an error that will forbid you to truncate a table that is referenced in a foreign key constrain.

You will get the following error

Cannot truncate a table referenced in a foreign key constraint...

as soon as you reach to the first


method call.


Open you main seeder file and scroll to



Right after opening bracket add

DB::statement('SET FOREIGN_KEY_CHECKS=0;');

and the just before closing bracket add

DB::statement('SET FOREIGN_KEY_CHECKS=1;');


public function run()

    // Disable foreign key check for this connection before running seeders
    DB::statement('SET FOREIGN_KEY_CHECKS=0;');


    // Enable foreign key check again
    DB::statement('SET FOREIGN_KEY_CHECKS=1;');

Now run

php artisan db:seed