0

I'm trying to write a migration script to truncate my vistors table. We usually place the revert of the up function in the down function.

But in this case, it's a truncate, what should I put in my down function ?

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class TruncateVisitorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
       DB::table('visitors')->truncate();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // what should I put here ? 
    }
}
code-8
  • 54,650
  • 106
  • 352
  • 604
  • 1
    What you put there depends on what you want? Seed/insert data if there was some fixed data that you truncated from the table.. If it had dynamic data(coming from your application) I wonder why are you truncating it? – codisfy Mar 25 '16 at 13:32
  • 4
    A true revertible migration would make a backup copy of the table visitors on `up()` before truncating and then copy the backup into the original on `down()`. That may be unnecessary for your needs. – Josh J Mar 25 '16 at 13:42
  • Thank you both for sharing your suggestions. :) – code-8 Mar 25 '16 at 14:18
  • @JoshJ is there a way to implement the step you mentioned? Cause i couldn't find any in Laravel docs – Abrar Jun 16 '20 at 08:19

1 Answers1

0

Here is one example I use:

public function up()
{
    Schema::create('users', function(Blueprint $table)
    {
        //
    });

    Schema::create('cats', function(Blueprint $table)
    {
        //
    });

    Schema::create('items', function(Blueprint $table)
    {
        //
    });
}

public function down()
{
    $tables = [
        'users',
        'cats',
        'items'
    ];

    foreach($tables as $table) Schema::drop($table);
}

You would use truncate in the beginning of a seeder.

user2094178
  • 9,204
  • 10
  • 41
  • 70