Skip to content

Instantly share code, notes, and snippets.

@andyg1
Created November 20, 2015 11:05
Show Gist options
  • Save andyg1/4d6ee6de61b031c13d65 to your computer and use it in GitHub Desktop.
Save andyg1/4d6ee6de61b031c13d65 to your computer and use it in GitHub Desktop.
Truncating Laravel tables before seeding them
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
protected $toTruncate = ['users'];
public function run()
{
Model::unguard();
foreach($this->toTruncate as $table) {
DB::table($table)->truncate();
}
$this->call(UsersTableSeeder::class);
Model::reguard();
}
}
@f-giftagram
Copy link

Thanks!

@simplenotezy
Copy link

simplenotezy commented Sep 6, 2021

You might want to disable foreign key checks as well:

<?php

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

class DatabaseSeeder extends Seeder
{
    protected $toTruncate = ['users'];

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

        Schema::disableForeignKeyConstraints();

        foreach($this->toTruncate as $table) {
            DB::table($table)->truncate();
        }

        Schema::enableForeignKeyConstraints();

        $this->call(UsersTableSeeder::class);

        Model::reguard();
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment