Introduction
Database migrations in Laravel provide a structured way to define and modify your database schema using PHP code instead of raw SQL. This feature makes database versioning, collaboration, and deployment more seamless and manageable.
By the end of this guide, you’ll understand how to create, modify, rollback, and seed migrations in Laravel efficiently.
What Are Migrations in Laravel?
Migrations act as version control for your database, allowing teams to work together without conflicts. Instead of manually editing tables, you write migration files that define schema changes, making it easier to track modifications over time.
Benefits of using migrations:
- Consistency: Ensures that every developer’s database structure is the same.
- Automation: Helps automate schema changes during deployment.
- Rollback Support: Easily revert schema changes if needed.
Setting Up Migrations in Laravel
To use migrations, ensure you have Laravel installed and configured with a database connection in .env
:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
Run the migration command to verify everything is working:
php artisan migrate
If successful, Laravel will create default tables like migrations
, users
, password_resets
, etc.
Creating a New Migration
To create a new migration, use the Artisan command:
php artisan make:migration create_posts_table
This generates a new migration file inside the database/migrations/
directory. The file name follows the format:
YYYY_MM_DD_HHMMSS_create_posts_table.php
Inside the migration file, you’ll find two methods:
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');
}
- The
up()
method defines the schema for creating theposts
table. - The
down()
method ensures that runningphp artisan migrate:rollback
will drop the table.
Run the migration using:
php artisan migrate
This will create the posts
table in your database.
Modifying an Existing Table
To alter an existing table, generate a new migration:
php artisan make:migration add_status_to_posts_table --table=posts
Modify the migration file to add a status
column:
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->string('status')->default('draft');
});
}
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('status');
});
}
Run the migration:
php artisan migrate
Now the posts
table will include a status
column with a default value of 'draft'
.
Rolling Back Migrations
If you need to undo the last migration:
php artisan migrate:rollback
To rollback all migrations:
php artisan migrate:reset
To rollback and re-run migrations:
php artisan migrate:refresh
Seeding Data After Migrations
To populate tables with sample data, use Laravel Seeders. First, create a seeder:
php artisan make:seeder PostSeeder
Edit database/seeders/PostSeeder.php
:
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class PostSeeder extends Seeder
{
public function run()
{
DB::table('posts')->insert([
'title' => 'First Post',
'content' => 'This is the first post.',
'status' => 'published',
'created_at' => now(),
'updated_at' => now(),
]);
}
}
Run the seeder:
php artisan db:seed --class=PostSeeder
To seed all available seeders, run:
php artisan db:seed
Migration Best Practices
1. Use Meaningful Migration Names
Instead of php artisan make:migration add_column
, use php artisan make:migration add_status_to_posts_table --table=posts
for clarity.
2. Always Define a down()
Method
This ensures safe rollbacks in case of issues.
3. Avoid Directly Modifying the Database
Rely on migrations instead of altering tables manually via SQL.
4. Run Migrations in Production Cautiously
Use php artisan migrate --pretend
to preview changes before execution.
5. Keep Migrations Organized
Delete old migrations once they become redundant after a schema update.
Conclusion
Laravel migrations streamline database management by offering a structured approach to schema modifications. Whether creating new tables, modifying columns, or rolling back changes, migrations keep database changes consistent and version-controlled.
By following best practices and leveraging migrations effectively, you can maintain a scalable and well-organized database structure in your Laravel projects. 🚀