Essentials of Laravel Migration

Aug 22, 2024

Understanding Migration in Laravel

What is Migration?

  • Migration is like version control for your database.
  • It allows teams to define and share the application's database schema.

The Migrate Command

  • Command: php artisan migrate
  • Purpose: Runs database migrations.
  • To understand what it does, use php artisan migrate --help or php artisan migrate -h.

Migration Files

  • Located in the database/migrations directory.
  • Naming Pattern: timestamp_create_table_name.php
    • Example: 2023_01_01_000000_create_users_table.php

Contents of Migration Files

  • Each migration file is responsible for defining one table's schema.
  • Example Fields in Users Table Schema:
    • ID (Integer)
    • Name (String)
    • Email (String, Unique)
    • Verified At (Timestamp)
    • Password (String)
    • Remember Token (String)
    • Timestamps (Created At, Updated At)

Running Migrations

  • After defining migrations, the command php artisan migrate creates defined tables in the database.
  • Example of created tables:
    • Users
    • Password Reset Tokens
    • Jobs
    • Personal Access Tokens

Migrations Table

  • Laravel maintains a migrations table that records the migrations that have been run.
  • This prevents migrations from being run multiple times.

Updating Migrations

  • To update a table, create a new migration using:
    • Command: php artisan make:migration update_users_table
    • Define what to change in the new migration file.
  • Rollback: To reverse changes, include down method in migration.

Example of Renaming a Column

  • Change column name to username:
    • Use Schema::table('users', function (Blueprint $table) { ... });
    • Don't forget to define the reverse operation in down method.

Checking Migration Status

  • Use php artisan migrate:status to check the current status of your migrations.

Final Notes

  • Always ensure migrations are well-defined for future updates.
  • Keep track of changes to maintain database integrity.