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

truncate()

method call.

Solution

Open you main seeder file and scroll to

run()

method.

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;');

Example

public function run()
{
    Eloquent::unguard();

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

    $this->createSettings();
    $this->createUsers(4);
    $this->createTags(15);
    $this->createArticles(1350);
    $this->createActivity();

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

Now run

php artisan db:seed