Laravel

How to use Migration and Schema Builder in Laravel

January 30, 2018

author:

How to use Migration and Schema Builder in Laravel

Migrations in Laravel work as version control for a database. This feature allows us to modify and share application database schema right from the project files. We can generate migration with a single artisan command: (P.S. Configure database settings before running any of these commands)

php artisan make:migration create_posts_table

Note that the newly created migrations are placed in database/migration directory. Also, migration files contain timestamp that lets Laravel determine the order of migrations in the database. We can also use an extra parameter while creating a migration to pre-fill the migration scaffolding for us. Here’s how we can do that:

php artisan make:migration create_posts_table --create=posts
# database/migrations/...create_posts_table.php

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
    }

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

# Migration Basics

With both these methods, we use Schema Builder to create or modify tables. As shown below, we can add columns to the table:

# database/migrations/...create_posts_table.php
...
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
    });
}
...

But simply creating migrations and adding fields to it won’t create a physical table in the database. We have to run the migrations. Like not literally! But, with an artisan command:

php artisan migrate
Laravel Migrate Command Console Output

If you are running migration for the first time in an application, Laravel will also run its default migrations, i.e., users and password_resets table. Laravel also creates an extra table named migrations for its internal database version control.

MySQL Database Schema

# Migration Roll Backs

In case of error or inconsistency, we can all rollback (i.e remove) the migration tables from the actual database. This single artisan command can rollback the last batch of migrations. For example, for us, in last batch we migrated 3 tables (users, reset_passwords and posts).

php artisan migrate:rollback

We can also rollback the whole database of our application with:

php artisan migrate:reset

For advanced migrations where we may need to rollback the current(or old) migration and migrate the tables again, we can use:

php artisan migrate:refresh

# Laravel Schema Builder

Let us now dive into some database schema building since our migration table ‘posts‘ is ready.

# Database Tables:

Create Tables

To create tables using Laravel, we use create method present in Schema facade. It expects two arguments – table name and closure function that receives Blueprint object to define the table schema.

Schema::create('posts', function (Blueprint $table) {
  $table->increments('id');
});

Rename Table

As you would have already guessed the rename() method of the Schema facade.

Schema::rename($from, $to);
Schema::rename($posts, $articles);

Drop Table

We can drop the existing table by simply calling drop() or dropIfExists method:

Schema::drop('posts');
Schema::dropIfExists('posts');

# Table Columns

Create Columns

As we used to create a method of Schema facade to create the database table, we can use table method to update the existing table and add columns or fields to it. It also expects the same two arguments as create method – table name and a closure.

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

Laravel supports all most all the datatypes that you would imagine using. A wide range of column types is available ranging from increments, integer, bigInteger, binary, boolean, char, date, dateTime, decimal, double, enum, float to ipAddress, json, longText, rememberToken, softDeletes, string, text, timestamps, etc.

Rename Column

To rename the column, we can use the renameColumn() method of the schema builder.

Schema::table('posts', function (Blueprint $table) {
  $table->renameColumn('from', 'to');
});

Drop Column

To drop a column from the database, we can use dropColumn() the same way as renameColumn(). Also, we can drop multiple columns at once using:

Schema::table('posts', function (Blueprint $table) {
  $table->dropColumn(['comments', 'views', 'category']);
});

# Creating Primary Key & Indexes

Laravel Schema Builder supports various types of indexes like: primary key, foreign key, unique, index, spatial index. Here are some examples:

Schema::table('users', function (Blueprint $table) {
  $table->primary('id');
  $table->string('title')->unique();
});

Conclusion:

In this Laravel specific post, we worked around the concept of migration. As we discussed, migrations are really powerful and can enhance the project development to great extent. We also saw database and schema building at a stretch.

Questions & Comments:

Thank you for reading. Got questions or tips to share on this tutorial of Schema Builder and Migration in Laravel? Shoot them in the comment section below.

Leave a comment

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