make a migration one way

Published 2 months ago by Phill93

Hi,

how can I create a migration that works only in one direction. I have on that modifys a relation from a one to many to a many to many, this way is possible without losing data. On the way back you are losing data if there are more than one relations.

Phill93

Best Answer (As Selected By Phill93)
lostdreamer_nl

in the up() method, check if the pivot table exists for the many to many relationship

If it does, return without running the migration.

Do not implement the down() method.

lostdreamer_nl

in the up() method, check if the pivot table exists for the many to many relationship

If it does, return without running the migration.

Do not implement the down() method.

Sergiu17

@Phill93 inside up() and down() you could write whatever you want, you can select all data and save into another table, you could create others tmp tables where you can store your data

public function up()
{
    $data = DB('table')->get();
    foreach($data as $item)
    {
        // insert into other table
    }

    // here goes your schema table
}

Phill93

@Sergiu17 my up function is finished.

I want a hard error if someone runs the rollback command.

lostdreamer_nl

throw an exception in the down method.

But that would remove your ability to ever rerun all migrations.

A better option I believe is what I said before: do a check in the up() method and only run the migration when needed and do not implement the down method.

36864
36864
2 months ago (61,750 XP)

But that would remove your ability to ever rerun all migrations.

php artisan migrate:fresh will still work since it doesn't use down() at all.

Please sign in or create an account to participate in this conversation.