Wednesday, 5 March 2025

Delete, add and edit columns using Laravel 12 migrations

 The following code example show how to delete, add and edit columns using Laravel 12 migrations. In all cases, when the migration has been completed, you run the command:
php artisan migrate

Delete example

php artisan make:migration delete_column_name_to_table_name --table=table_name

public function up(): void

    {

        Schema::table('table_name', function (Blueprint $table) {

            $table->dropColumn('column_name');

        });

    }


    public function down(): void

    {

        Schema::table('table_name', function (Blueprint $table) {

            $table->string('column_name'); // Define the column type to restore it

        });

    }

Add example

php artisan make:migration add_column_name_to_table_name --table=table_name

public function up(): void

    {

        Schema::table('table_name', function (Blueprint $table) {

            $table->string('column_name')->nullable();

        });

    }


    public function down(): void

    {

        Schema::table('table_name', function (Blueprint $table) {

            $table->dropColumn('column_name');

        });

    }

Edit example

php artisan make:migration edit_column_name_to_table_name --table=table_name

public function up(): void

    {

        Schema::table('table_name', function (Blueprint $table) {

            $table->string('column_name', 100)->nullable()->change();

        });

    }


    public function down(): void

    {

        Schema::table('table_name', function (Blueprint $table) {

            $table->string('column_name', 255)->notNullable()->change();

        });

    }

No comments:

Post a Comment