chepew23
11/25/2018 - 8:28 PM

Truncate tables with foreign key constraints in a Laravel 5.7 seed file.

Truncate tables with foreign key constraints in a Laravel 5.7 seed file.

<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class DatabaseSeeder extends Seeder
{
    // Your tables to truncate
    protected $toTruncate = ['user'];

    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // This is a simple strategy for truncate your database.
        
        // Disabled massive assignament restriction
        Model::unguard();
        // Disable foreign key check for this connection before running seeders
        Schema::disableForeignKeyConstraints();

        // Note: truncate strategy failed with SQL Server (and others).
        foreach($this->toTruncate as $table) {
            DB::table($table)->delete();
        }
        
        /**
        * Your factories exections.
        * For example:
        * ************
        *
        * factory(User::class, 1000)->create();
        *
        */

        // Enable constraints
        Schema::enableForeignKeyConstraints();
        // Enable massive assignament restriction
        Model::reguard();
    }
}

Please, don't use for disable foreign key constraints:

  DB::statement('SET FOREIGN_KEY_CHECKS=0;');
  // and
  DB::statement('SET FOREIGN_KEY_CHECKS=1;');

This is a MySQL specific statement, and your are using a ORM. The previous statement doesn't work in other database system (for example: MSSQL). Use something like what I describe in my DatabaseSeeder.php file.