Laravel Migrations


Example

To control your database in Laravel is by using migrations. Create migration with artisan:

php artisan make:migration create_first_table --create=first_table

This will generate the class CreateFirstTable. Inside the up method you can create your columns:

<?php

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

class CreateFirstTable extends Migration
{
    public function up()
    {
        Schema::create('first_table', function (Blueprint $table) {
            $table->increments('id');
            $table->string('first_string_column_name');
            $table->integer('secont_integer_column_name');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop('first_table');
    }
} 

At the end to run all of your migrations classes you can run the artisan command:

php artisan migrate

This will create your tables and your columns in your database. Other useful migrate command are:

  • php artisan migrate:rollback - Rollback the last database migration
  • php artisan migrate:reset - Rollback all database migrations
  • php artisan migrate:refresh - Reset and re-run all migrations
  • php artisan migrate:status - Show the status of each migration

Modifying existing tables

Sometimes, you need to change your existing table structure like renaming/deleting columns. Which you can accomplish by creating a new migration.And In the up method of your migration.

//Renaming Column.

public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->renameColumn('email', 'username');
    });
}

Above example will rename email column of users table to username. While the below code drops a column username from users table.

IMPROTANT : For modifying columns you need to add doctrine/dbal dependency to project's composer.json file and run composer update to reflect changes.

//Droping Column
public function up()
{
    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn('username');
    });
}