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

less than a minute of reading

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. This article explains how to bypass the problem.

Context

The error we are talking about is:

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

and you will get it as soon as you reach the first call to the truncate() method in any of your seeders.

Solution

Open you main seeder file and scroll to the run() method.

Right after the opening bracket add:

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

and just before the closing bracket add:

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

Example code may look like:

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

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

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

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

Finally run php artisan db:seed. Error should be gone.


Words: 169
Published in: Laravel · PHP
Last Revision: October 25, 2022

Related Articles   📚