When you start learning web development, managing database tables can feel intimidating. Have you ever accidentally deleted a table or forgotten what columns you added last week? In Laravel, Migrations solve this problem by acting like version control (like Git) for your database structure.
What is a Migration?
Imagine you and your friend are building a Lego castle together. Instead of trying to guess each piece you added, you write down step-by-step assembly instructions in a shared notebook. In Laravel, a migration file is that exact set of instructions. It tells your database exactly how to create, modify, or remove tables.
Creating Your First Migration
Laravel provides a friendly command-line tool called Artisan. To create a migration file for a new table called tasks, open your terminal and run:
# Generate a new database migration file
php artisan make:migration create_tasks_tableLaravel creates a fresh PHP file inside database/migrations/. Open it up, and you will see two simple functions: up() and down():
public function up(): void
{
Schema::create('tasks', function (Blueprint $table) {
$table->id(); // Automatic ID number
$table->string('title'); // Short text for task title
$table->boolean('is_completed')->default(false); // Checkbox yes/no
$table->timestamps(); // Created and updated dates
});
}Running the Migration
To actually build the table in your database, execute this single Artisan command:
# Apply your migration to create the table
php artisan migrateYour database now has the tasks table ready to use!
3 Things to Remember
- The Concept: Migrations are version control blueprints for your database tables.
- The up() Method: Defines what happens when you build the table (e.g., adding columns).
- The migrate Command: Run
php artisan migrateto apply all pending blueprints.