How to Change Column Name and Type in Laravel Migration

  2246 views   5 months ago Laravel

In the working with MySQL database, sometimes you need to column type. You feel that the column you have created as enum should be integer or you want to add more option in enum. In that cases changing it directly from MySQL is not good option because other member wouldn't get this changes in their table.

In this article, we will share you how you can change your existing column that you have already created. This can be done by creating new migration and run it.

Before starting on that, first you need to add doctrine/dbal package in your Laravel application. So first install it with Composer command.

composer require doctrine/dbal

After installing package now run artisan command to create new migration file.

php artisan make:migration change_columns_in_users_table

Suppose you want to change varchar to text about column, rename name field to first_name, adding last_name column after first_name. Here is the example below.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class ChangeColumnsInUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->text('about')->nullable()->change();
            $table->renameColumn('name', 'first_name');
            $table->string('last_name', 50)->nullable()->after('first_name');
            $table->dropColumn('token');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
}

Renaming and modifying enum column is not supported in doctrine/dbal, so if you want to update or rename enum column, you need to use DB::statement() instead of Schema::table() method.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class ChangeColumnsInUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        \DB::statement("ALTER TABLE `users` CHANGE `status` `status` ENUM('0', '1', '2') NOT NULL DEFAULT '0';");
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            //
        });
    }
}

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]