Migrations and Seeders
⏱ Estimated reading time: 2 min
Migrations and seeders in Laravel are used to manage the database structure and populate it with data. They help maintain consistency across development, testing, and production environments by allowing databases to be created and updated programmatically.
1. What Are Migrations?
Migrations are version control for the database. They define the structure of database tables using PHP instead of writing raw SQL.
Migrations are stored in:
2. Creating a Migration
To create a migration file:
To create a migration along with a model:
3. Migration File Structure
Example migration:
-
up(): Creates or modifies tables
-
down(): Reverts the changes
4. Running Migrations
Run all pending migrations:
Rollback the last migration:
Refresh migrations:
5. Modifying Existing Tables
Create a new migration to update a table:
Example:
6. What Are Seeders?
Seeders are used to insert sample or default data into database tables. They are helpful for testing and initial setup.
Seeders are stored in:
7. Creating a Seeder
Example seeder:
8. Running Seeders
Run all seeders:
Run a specific seeder:
Run migrations and seeders together:
9. Using Model Factories with Seeders
Factories generate fake data automatically:
Usage:
10. DatabaseSeeder
The main seeder file:
Example:
Conclusion
Migrations and seeders provide a structured, reliable way to manage database schemas and data in Laravel. They improve collaboration, make database changes reversible, and ensure consistency across environments, making Laravel applications easier to develop and maintain.
Register Now
Share this Post
← Back to Tutorials