Search code examples
laraveleloquentlaravel-query-builderlaravel-migrations

What is the down() function to reverse this Laravel migration that I make?


So, I want to add a column ('Semester_TA') and change the property of this column ('kode_mk') to be unique value, so I created this migration:

    public function up()
    {

    Schema::table('mk', function(Blueprint $table){
        $table->string('Semester_TA')->after('sks');
        $table->string('kode_mk')->unique();
    });

    Schema::table('lr2', function(Blueprint $table){
        $table->dropForeign(['id']);
    });
    }
    public function down()
    {
     //
    }

I also want to drop/delete this foreign key ('id') that I created as it sometimes give a constraint error in my project. My question is what function down should I write to reverse the update above that i'm about to do in case of migration fails or error?

this is the table "mk" and "lr2" migrations that i use right now:

   Schema::create('mk', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('kode_mk');
        $table->string('mk');
        $table->integer('sks');
        $table->integer('semester');
        $table->integer('available_seats');
        $table->timestamps();
    });
   Schema::create('lr2', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('k_mk');
        $table->string('mk');
        $table->string('angkatan');
        $table->integer('request_seats');
        $table->boolean('status_request');
        $table->timestamps();

        $table->foreign('id')->references('id')->on('mk');
    });

Solution

  • First, you have to create a new migration:

    php artisan make:migration Add_column_change_the_property

    Then in that migration file up(), try:

    public function up()
        {
    
        Schema::table('mk', function(Blueprint $table){
            $table->string('Semester_TA')->after('sks');
            $table->string('kode_mk')->unique();
        });
    
           }
    

    Then in the migration file down() try:

    public function down()
    {
       $table->dropColumn('kode_mk');
        $table->foreign('id')->references('id')->on('mk');
     //
    }
    

    Then migrate the file by:php artisan migrate