LARAVEL

Laravel Migration structure


In Laravel, migration files follow a structured format to define changes to your database schema. Here's an overview of the migration structure:

 

Migration File Naming Convention:

  • Migration files are typically named with a timestamp followed by an underscore and a descriptive name, such as 2022_03_13_093215_create_users_table.php. The timestamp ensures that migrations are executed in the order they were created.

 

Migration Class:

  • Each migration file contains a PHP class that extends the Migration class provided by Laravel.
  • The class name should be descriptive of the migration's purpose. For example, for creating a users table, you might have a class named CreateUsersTable.
  • The class definition usually includes an up() method to define the actions to be performed when migrating up, and a down() method to define the actions to be performed when rolling back the migration.

 

Schema Building:

  • Inside the up() method, you use Laravel's Schema Builder to define changes to the database schema. This includes creating or modifying tables, adding or dropping columns, defining indexes, and more.
  • Laravel provides a fluent interface for building schema changes, making it easy to express complex changes in a concise and readable way.

 

Rollback Operations:

  • Inside the down() method, you define the operations to be performed when rolling back the migration. This typically involves reversing the actions performed in the up() method to revert the database schema changes.

 

Migration Annotations:

  • Optionally, you can add annotations to your migration class to provide additional information or instructions. For example, you might use @package, @author, or @since annotations to document the purpose and history of the migration.

 

Example:

<?php

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

class CreateUsersTable extends Migration
{
    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();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Note - This migration file creates a users table with columns for name, email, email_verified_at, password, remember_token, and timestamps for created_at and updated_at. The down() method drops the users table if the migration is rolled back.


LARAVEL