Migrations In Laravel

Migrations are like version control for your database, allowing your team to easily modify and share the application’s database schema.

Migrations are typically paired with Laravel’s schema builder to easily build your application’s database schema.

If you have ever had to tell a teammate to manually add a column to their local database schema, you’ve faced the problem that database migrations solve.

Generating Migrations

To create a migration, use the make:migration

php artisan make:migration create_users_table

The new migration will be placed in your database/migrations directory.

Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

The –table and –create options may also be used to indicate the name of the table and whether the migration will be creating a new table.

These options pre-fill the generated migration stub file with the specified table:

php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users

If you would like to specify a custom output path for the generated migration, you may use the –path option when executing the make:migration command. The given path should be relative to your application’s base path.

Migration Structure

A migration class contains two methods: up and down.

The up method is used to add new tables, columns, or indexes to your database.

The down method should reverse the operations performed by the up method.

Within both of these methods, you may use the Laravel schema builder to expressively create and modify tables.

For example, this migration example creates a flights table:

<?php

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

class CreateFlightsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

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

Running Migrations

To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

1 thought on “Migrations In Laravel”

  1. Appreciating the persistence you put into your website and in depth information you offer. It’s awesome to come across a blog every once in a while that isn’t the same unwanted rehashed information. Fantastic read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

Leave a Comment

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