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.
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:
To create a migration file:
To create a migration along with a model:
Example migration:
up(): Creates or modifies tables
down(): Reverts the changes
Run all pending migrations:
Rollback the last migration:
Refresh migrations:
Create a new migration to update a table:
Example:
Seeders are used to insert sample or default data into database tables. They are helpful for testing and initial setup.
Seeders are stored in:
Example seeder:
Run all seeders:
Run a specific seeder:
Run migrations and seeders together:
Factories generate fake data automatically:
Usage:
The main seeder file:
Example:
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.
Take quizzes related to this topic and see where you stand!
Start Quiz Now