'Why do I need to call Schema::table in Laravel more than once?

I'm on a Udemy course about Laravel 7. In a particular class, I need to rename the column of a table called site_contacts. When I try to simplify the code and I and put two instructions in a callback the error occurs: There is no column with name 'contact_reason_id' on table 'site_contacts'. This occurs when you reach the statement to change the column type. But, if I write separately, as it is in the code, migration runs without problems.

I would like to understand why it needs to be done this way and if there's any better way. Initially, I think the class needs to start with its updated internal attributes to proceed with the statements, otherwise it doesn't know that the column is under another name.

This code does not work.

public function up()
    {
        Schema::table('site_contacts', function (Blueprint $table) {
            // There is no column with name 'contact_reason_id' on table 'site_contacts'.
            $table->renameColumn('contact_reason', 'contact_reason_id');
            $table->unsignedBigInteger('contact_reason_id')->change();
        });

        Schema::table('site_contacts', function (Blueprint $table) {
            $table->foreign('contact_reason_id')->references('id')->on('contact_reasons');
        });
    }

This code works.

public function up()
{
    Schema::table('site_contacts', function (Blueprint $table) {
        $table->renameColumn('contact_reason', 'contact_reason_id');
    });

    Schema::table('site_contacts', function (Blueprint $table) {
        $table->unsignedBigInteger('contact_reason_id')->change();
    });

    Schema::table('site_contacts', function (Blueprint $table) {
        $table->foreign('contact_reason_id')->references('id')->on('contact_reasons');
    });
}

public function down()
{
    Schema::table('site_contacts', function (Blueprint $table) {
        $table->dropForeign('site_contacts_contact_reason_id_foreign');
        $table->dropIndex('site_contacts_contact_reason_id_foreign');
    });

    Schema::table('site_contacts', function (Blueprint $table) {
        $table->integer('contact_reason_id')->change();
    });

    Schema::table('site_contacts', function (Blueprint $table) {
        $table->renameColumn('contact_reason_id', 'contact_reason');
    });
}

Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source