Recently I have started working on Laravel project and playing with migration for the first time and realized that managing database with migration, it very easy to handle. In this tutorial, I will explain how to create the migration and how to change columns type.

Let’s create a games table with the migration, so first open your terminal and navigate to your project directory and hit below command:

php artisan make:migration create_games_table

The new migration will be placed in your database/migrations directory. Now open your games migration file and add Schema to your up method:

Schema::create('games', function (Blueprint $table) {
    $table->integer('id', '11')->increments();
    $table->integer('game_id')->nullable();
    $table->integer('title')->nullable();
    $table->string('color')->nullable();
    $table->string('long_title')->nullable();
    $table->string('square_image')->nullable();
    $table->string('circle_image')->nullable();
    $table->string('rectangle_image')->nullable();
    $table->dateTimeTz('created_at')->nullable();
    $table->dateTime('updated_at')->nullable();
    $table->dateTime('deleted_at')->nullable();
});

Run migration command to generate your games table:

php artisan migrate

Now after creating a table, I realized that I have done mistake in the title field and I used the title as an integer type and it must have string type so now what to do. Well, it’s very easy to replace the type with the migration.

Create a new migration and add Schema to your up method:

Schema::table('games', function($table)
{
    $table->string('title')->change();
});

You just need to add change() function at the end of the chain and it will correct your type.

If you are getting below error after running migration don’t afraid.

[RuntimeException]                                                                   
Changing columns for table "games" requires Doctrine DBAL; install "doctrine/dbal".

You must install doctrine/dbal so type composer require doctrine/dbal in your terminal.

Happy Coding 😉

Categories: LaravelPHP

Leave a Reply

Your email address will not be published. Required fields are marked *