Migrations and Seeders

📘 Laravel 👁 54 views 📅 Dec 22, 2025
⏱ 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:

database/migrations

2. Creating a Migration

To create a migration file:

php artisan make:migration create_users_table

To create a migration along with a model:

php artisan make:model Post -m

3. Migration File Structure

Example migration:

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'); }
  • up(): Creates or modifies tables

  • down(): Reverts the changes


4. Running Migrations

Run all pending migrations:

php artisan migrate

Rollback the last migration:

php artisan migrate:rollback

Refresh migrations:

php artisan migrate:refresh

5. Modifying Existing Tables

Create a new migration to update a table:

php artisan make:migration add_status_to_posts_table

Example:

$table->string('status')->default('draft');

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:

database/seeders

7. Creating a Seeder

php artisan make:seeder PostSeeder

Example seeder:

public function run() { \App\Models\Post::create([ 'title' => 'First Post', 'content' => 'This is a sample post' ]); }

8. Running Seeders

Run all seeders:

php artisan db:seed

Run a specific seeder:

php artisan db:seed --class=PostSeeder

Run migrations and seeders together:

php artisan migrate --seed

9. Using Model Factories with Seeders

Factories generate fake data automatically:

php artisan make:factory PostFactory --model=Post

Usage:

Post::factory(10)->create();

10. DatabaseSeeder

The main seeder file:

database/seeders/DatabaseSeeder.php

Example:

public function run() { $this->call([ PostSeeder::class, ]); }

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.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes