Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

meredevelopment's avatar

Updating column data within Migration, is this ok?

Hi, I have a situation where I need to change the schema for an established Laravel app. I'm removing a model called 'customer' and all its relationships etc. Part of this work is to duplicate an existing column that references another, and then delete it. So I have this migration:

Schema::table('tableone', function (Blueprint $table) {
    $table->bigInteger('user_id')->unsigned()->after('mid');
    $table->string('customer_surname', 50)->nullable()->after('user_id');
    $table->string('customer_forename', 20)->nullable()->after('user_id');
    $table->string('customer_title', 20)->nullable()->after('user_id');
});

DB::statement('UPDATE tableone
    INNER JOIN customers ON tableone.customer_id = customers.id
    SET 
    tableone.user_id = customers.user_id,
    tableone.customer_title = customers.title,
    tableone.customer_forename = customers.forename,
    tableone.customer_surname = customers.surname');

Schema::table('tableone', function (Blueprint $table) {
    $table->foreign('user_id')->references('id')->on('users');
    $table->dropForeign('tableone_customer_id_foreign');
    $table->dropColumn('customer_id');
});

As you can see, I'm creating a new column called user_id, using the DB::statement to populate it with data from the existing customer_id column, then adding a foreign key for user_id and dropping customer_id. If I don't run the update query, this would work fine on fresh installs, but barfs with a "foreign key constraint" failure when run on a full DB.

So... this works but seems kinda fishy to me - changing data in a Migration. Is there a better away to do this? Should the UPDATE be in a seeder and if so, how do I make sure that seeder is run at the right point when deploying this?

Open to ideas and all related criticism thanks!

0 likes
2 replies
martinbean's avatar
Level 80

@meredevelopment No. This is something I do myself. If you need to move data to retain integrity in your database, then it’s fine to do that in a migration. I migration isn’t just creating and updating tables and columns.

If you extracted it to a seeder then you wouldn’t be able to control when that seeder was ran, i.e. if you had two migrations that needed to run, but migration #2 relied on data in the seeder.

2 likes
meredevelopment's avatar

Thanks for confirming that Martin, I feel this is one of those 'use sparingly only when necessary' techniques. But it work well 👍

Please or to participate in this conversation.