Sabbir Ahmed

Sabbir Ahmed

1 month ago

Laravel Migration Tutorial: Create, Add Columns, Rename, and Rollback Guide

Laravel framework makes it very easy for developers to perform database operations. It provides a handy way to create and manage database through migrations. Being a MVC (Model View Controller) framework, Laravel migration is one of the powerful and popular features of this framework. We dont have to write complex or bad looking SQL commands to create tables and bind those tables to our models. Rather with writing less and smart code with the support of this framework, database management becomes very easy for developers. Even we dont have to touch the database, we can make changes as we require, which is one of the reason, this framework is so powerful and supportive to build large scale applications. In this tutorial we will how to write Laravel migrations, add, rename or modify migrations efficiently. 

Laravel Migrations 101: Effortlessly Craft and Manage Tables with Laravel


First lets create a fresh new laravel application to work with migrations: 


composer global require laravel/installer

Then please connect your database to the application with .env:


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password

  • Create a new migration


Lets say, we have a User model and we plan to have some simple fields in the users table like this: 

Users
  • Name - varchar 
  • Email - varchar - unique 
  • Password - varchar 

So, then create a migration file for the User model:


php artisan make:migration create_users_table --create=users

This will create a new file under database/migrations

Now lets update the migration file like this:


<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

You can see there are two methods up and down. The up method defines the action or what to do during we run this migration file. The down method works when you need to rollback with the migrations you have already run and return back to previous state of the database.

For id, we are using id() method from laravel, which is a blueprint or shorthand for ‘id’ field as big integer and auto incrementing column. Thus laravel provides a fluent interface to help us write codes faster. 

Email_verified_at and rememberToken are for verifying user email and remembering login sessions respectively. 

And timestamps will produce created_at and updated_at columns in the database, which maintains data creation and modifying dates automatically. 

To migrate the fields to the database, you can run: 


php artisan migrate

  • What if I want to rollback?


Now you might wonder that, I have run a migration, but after that I want to rollback for make some changes which I forgot to do. 

To rollback you should run:


    
php artisan migrate:rollback

Now this command will execute the down method from the migration. Which means, it will undo whatever changes has been made to database. According to our logic defined above, it will remove the users table from database which will serve our purpose. 

  • Rollback further


The example above will rollback the last migration or for a single step back. 

But suppose you have run 2 or 3 consecutive migrations and you want to rollback all at once. So in these case you define step in the command, how many steps should be considered while rolling back: 


php artisan migrate:rollback --step=3

Adding and Removing Columns with Migrations


After generating a migration file, we often need to make changes to the table as we move forward with the application. We can also achieve that with creating multiple migration files for same table. It never means, we write a table once and we cant modify our table structure if necessary. Lets see a quick example how we can achieve that. 

  • How would I update existing tables with migration? 


Assume, we have created a new table users with following the article above. Now, suppose we need add a field with which we will check the user’s role as admin or not. To do that we want to add a field, for example ‘is_admin’ in the users table. 

Lets create a new migration to add the field to users table:


php artisan make:migration add_is_admin_to_users_table --table=users

This will create a new migration file under database/migrations

Please update the file as below: 


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

class AddIsAdminToUsersTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('is_admin')->default(false);
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('is_admin');
        });
    }
}

We have added a boolean field is_admin with a default value false

Now migrate it to database:


php artisan migrate

So thats how we can make changes to our existing tables. You can also remove columns in this way if you want. This will only apply the changes to database and of course your previous data wont be affected if you dont write any commands related to them. 

Renaming Database Columns with Ease


Most of time in a migration, we just have to create new tables or modify old tables. Alongside that, we also sometimes need to rename an old column. Laravel’s default schema doesnt actually support directly these kind of operation. For these cases, we need to take help from packages like doctrine/dbal. Lets see a quick example of this kind of functionality.

  • How to rename existing column on database?


We already have installed a laravel app and have some table migrated to database. 

Now, to rename a column on existing table, first you have to install the doctrine/dbal package:


composer require doctrine/dbal

Now, create a new migration with this command: 


php artisan make:migration rename_column_in_table_name --table=table_name

Replace the table_name with your real table name and the column with real column name. 

Now a new migration file will be generated. You can make the following changes on the file like below: 


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

class RenameOldNameColumnInExampleTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('example_table', function (Blueprint $table) {
            $table->renameColumn('old_name', 'new_name');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('example_table', function (Blueprint $table) {
            $table->renameColumn('new_name', 'old_name');
        });
    }
}

Replace the example_table, old_name and new_name with your own table name, old column name and new column name. 

You can see, renameColumn method will now work for renaming the particular column of your table. This method requires the package doctrine/dbal to be installed in the system, otherwise you will face error.

  • Run the migration


Now you can run the migration and check the database if it is successfully renamed the column:


php artisan migrate

Renaming column is also as important as creating and modifying tables. You will need this kind of operations in many step of laravel development. 

Lets Dive Deeper on Doctrine/DBAL Package


For some functionalities like renaming or changing a particular column, we sometimes need help from other package like doctrine/dbal. It sometimes make question, why do we need this package in laravel? We have seen how we can rename column names with this package. But not only this, we can use this package for other kinds of database operations too.  

  • Some uses of doctrine/dbal


Laravel migration doesnt have the default schema for renaming columns or modifying attributes. We use this package mostly for enhancing the power of laravel migration schemas. Lets see some quick examples for other cases where we might need this package: 

1.  Renaming Columns: When you need to rename a column in a table.


$table->renameColumn('old_name', 'new_name');

2. Changing Column Types: When you need to change the data type of an existing column.


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

3. Renaming Indexes: When you need to rename an index on a table.


$table->renameIndex('old_index', 'new_index');

4. Dropping Indexes by Name: When you need to drop an index by its name (rather than by the column(s) it indexes).


$table->dropIndex('index_name');

5. Modifying Column Attributes: When you need to modify attributes of a column, such as changing it to nullable or setting a default value.


$table->integer('column_name')->nullable()->change();

All of these operations will need the package doctrine/dbal. Without the package, you will face error when using these methods. 

Summary


Laravel provides a beautiful framework for creating and managing tables with migrations, with least coding required. Other facilities like rollback just empowers developers and boost workflow. We can easily run and build tables with just few commands, also we can undo from any point to previous.  
Using package like doctrine/dbal is quite important and this package provides the same coding structure as laravel does, so we can have a consistent and similar approach while coding. These are powerful features which make building applications very convenient for devs. Having a good knowledge in depth of the migration rules will always help you stay ahead in the development. 

Thanks for your visit to this article. Hope you found it useful. Please let me know your thoughts in the comments. 

I wish you a great day.  

Comments

Login As User
Word Count: 0