Think of Laravel migrations as a version control system for your database. Just like Git keeps track of changes in your code, migrations keep track of changes in your database structure.
Instead of manually creating or modifying tables in MySQL, you write migration files in Laravel, and Laravel updates the database for you.
Simple Example: Creating a “Users” Table
Let’s say you want to create a users
table in your database.
Step 1: Create a Migration File
Run this Artisan command:
php artisan make:migration create_users_table
This will generate a migration file in the database/migrations/
folder.
Step 2: Define the Table Structure
Open the generated migration file (it will have a timestamp in the filename) and modify the up()
method:
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(); // Auto-increment primary key
$table->string('name'); // Name column
$table->string('email')->unique(); // Unique email column
$table->string('password'); // Password column
$table->timestamps(); // Created_at and updated_at columns
});
}
public function down()
{
Schema::dropIfExists('users'); // Drops the table if migration is rolled back
}
}
Step 3: Run the Migration
Now, run the migration to create the table in your database:
php artisan migrate
Laravel will execute the up()
method, creating the users
table.
Rolling Back a Migration
If you made a mistake or need to undo the migration, run:
php artisan migrate:rollback
This executes the down()
method and removes the users
table.
Modifying an Existing Table
If you want to add a new column to the users
table, create a new migration:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('phone')->nullable(); // Adding phone column
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('phone'); // Removing phone column if rolled back
});
}
php artisan make:migration add_phone_to_users_table --table=users
Then, update the up()
method in the new migration file:
Run the migration again:
php artisan migrate
Why Use Migrations?
✅ Keeps database changes trackable (just like version control)
✅ Works across multiple environments (no need to manually edit the database)
✅ Easy to modify and roll back
Final Thought
Instead of manually creating tables in MySQL, Laravel migrations make database management structured, efficient, and easy to track. 🚀