0
0
LaravelConceptBeginner · 3 min read

What is Migration in Laravel: Explanation and Example

In Laravel, migration is a way to create and modify database tables using PHP code instead of manual SQL commands. It helps developers manage database changes easily and share them with the team in a consistent way.
⚙️

How It Works

Think of migration in Laravel like a recipe for your database. Instead of cooking directly on the stove (writing raw SQL), you write down the steps (migration code) that anyone can follow to create or change the database structure.

When you run migrations, Laravel reads these recipes and applies the changes to your database. This way, your database stays organized and consistent across different computers or servers.

It also allows you to roll back changes if something goes wrong, just like undoing a step in a recipe.

💻

Example

This example shows a migration that creates a posts table with columns for id, title, and content.

php
<?php

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

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
Output
Creates a new database table named 'posts' with columns: id, title, content, created_at, and updated_at.
🎯

When to Use

Use migrations whenever you need to create or change database tables in a Laravel project. They are especially helpful when working in a team, so everyone can apply the same database changes easily.

For example, when adding a new feature that requires a new table or modifying an existing table's columns, you write a migration. This keeps your database structure version-controlled and easy to update.

Key Points

  • Migrations are PHP classes that define database changes.
  • They help keep database structure consistent across environments.
  • You can run migrations with php artisan migrate and roll back with php artisan migrate:rollback.
  • Migrations replace manual SQL scripts for easier teamwork and version control.

Key Takeaways

Laravel migrations let you manage database changes using PHP code instead of raw SQL.
They keep your database structure consistent and easy to share with your team.
Use migrations to create, modify, or delete tables in a version-controlled way.
Run migrations with artisan commands to apply or roll back changes safely.