Migrations
Define your database tables in code — version-controlled and shareable.
What you will learn
- Create tables with migrations
- Run and roll back migrations
- Understand why migrations matter
Tables as code
Migrations define your tables in PHP files instead of clicking around in phpMyAdmin. They are version-controlled, so your whole team builds the same database with one command.
php artisan make:migration create_products_tableThis creates a new, empty migration file inside database/migrations with a timestamp in its name (so migrations always run in the order you made them). Next you open that file and describe the columns your table should have.
Inside the file is an up() method — the code that runs when you build the table. Each line adds one column:
// database/migrations/...create_products_table.php
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->decimal('price', 8, 2);
$table->boolean('in_stock')->default(true);
$table->timestamps();
});
}Reading the columns: $table->id() adds an auto-incrementing primary key. $table->string('name') adds a text column for the product name. $table->decimal('price', 8, 2) adds a price with up to 8 digits, 2 after the decimal point. $table->boolean('in_stock')->default(true) adds a true/false column that defaults to true. $table->timestamps() adds created_at and updated_at columns automatically. You are describing the table in plain PHP instead of writing CREATE TABLE SQL by hand.
Once the file describes your table, these commands build it (or undo it) in the real database:
php artisan migrate # create the tables
php artisan migrate:rollback # undo the last batchNote: First, set your database name and credentials in the .env file. Then php artisan migrate builds the tables. $table->id() and $table->timestamps() add the id and created/updated columns automatically.
The whole migration workflow, in order:
- Run
php artisan make:migration create_products_tableto generate an empty migration file. - Open that file and describe your columns inside the
up()method. - Set your database name and login details in the
.envfile so Laravel can connect. - Run
php artisan migrate— Laravel reads your file and creates the real table. - If you made a mistake, run
php artisan migrate:rollbackto undo the last batch, fix the file, then migrate again.
Q. What are migrations for?
✍️ Practice
- Create and run a migration for a
productstable. - Roll it back, then migrate again.
🏠 Homework
- Write migrations for a blog (posts and users tables).