• Fri, Mar 2026

Laravel Database Essentials: Introduction to Migrations and Seeders

Laravel Database Essentials: Introduction to Migrations and Seeders

This comprehensive tutorial explains Laravel’s database essentials with a deep dive into migrations and seeders. You’ll learn step by step how to design database schemas, manage versions, and seed test data. This professional guide is designed for beginners and intermediate developers who want to master Laravel’s database layer for building scalable applications.

Introduction

Every dynamic application needs a reliable and flexible database structure. Laravel, being one of the most developer-friendly frameworks, provides two powerful tools for managing databases: migrations and seeders.

Think of migrations as version control for your database schema and seeders as factories for populating data. With migrations, you can create, modify, and share your database structure with ease. With seeders, you can generate sample or essential data for testing and production.

Why Use Migrations and Seeders?

Migrations Benefits

  • Version control for your database schema
  • Collaboration across teams without conflicts
  • Automated schema creation and modification
  • Easy rollback if something goes wrong

Seeders Benefits

  • Populate testing data quickly
  • Pre-fill essential data like admin users or roles
  • Repeatable and sharable data creation
  • Integration with factories for bulk fake data

Setting Up Database Connection in Laravel

Before we dive into migrations and seeders, configure your database connection in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=    

Laravel will use these credentials to connect to your database. You can check configurations in config/database.php.

Introduction to Migrations

A migration is simply a PHP class that defines changes to your database structure. Migrations live in the database/migrations directory.

php artisan make:migration create_users_table    

This will generate a new migration file with a timestamp prefix.

Understanding a Migration File

Here’s what a typical migration file looks like:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('users');
    }
};    

Key Parts:

  • up(): Defines what happens when the migration is run.
  • down(): Defines how to rollback the migration.

Running and Rolling Back Migrations

Run all migrations with:

php artisan migrate    

Rollback the last batch of migrations:

php artisan migrate:rollback    

Reset all migrations:

php artisan migrate:reset    

Refresh all migrations (rollback + re-run):

php artisan migrate:refresh    

Fresh migrate (drop all tables then migrate):

php artisan migrate:fresh    

Common Migration Column Types

Laravel’s schema builder provides many column types.

Column TypeUsageExample
stringVARCHAR$table->string('name', 100);
textLONGTEXT$table->text('description');
integerINT$table->integer('age');
booleanTRUE/FALSE$table->boolean('is_active');
timestampscreated_at & updated_at$table->timestamps();

Adding Foreign Keys

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
    $table->timestamps();
});    

Here, user_id is a foreign key referencing users.id.

Introduction to Seeders

Seeders are classes that populate your database with test or essential data. They live inside database/seeders.

php artisan make:seeder UserSeeder    

Writing a Seeder

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\User;

class UserSeeder extends Seeder
{
    public function run(): void
    {
        User::create([
            'name' => 'Admin',
            'email' => 'admin@example.com',
            'password' => bcrypt('password'),
        ]);
    }
}    

To run all seeders, execute:

php artisan db:seed    

Using Database Seeder

The DatabaseSeeder.php file calls other seeders:

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

Combining Seeders with Factories

Factories allow you to generate bulk fake data.

php artisan make:factory UserFactory --model=User    

Inside the factory:

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'password' => bcrypt('password'),
        ];
    }
}    

Now use this in a seeder:

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

Seeding Specific Environments

You may want different seeders for local and production.

if (app()->environment('local')) {
    $this->call(UserSeeder::class);
}    

Best Practices for Migrations and Seeders

  • Keep migrations small and specific.
  • Never edit old migrations that are already shared.
  • Use seeders for essential and reproducible data.
  • Combine factories with seeders for realistic test data.
  • Version control your migrations with Git for team collaboration.

Conclusion

Laravel migrations and seeders give you powerful control over your database structure and data population. Migrations ensure your schema evolves consistently across environments, while seeders provide the ability to populate databases with essential or testing data.

By mastering migrations and seeders, you gain confidence in handling databases professionally in Laravel projects. Whether you are building a small prototype or a large-scale enterprise system, these tools will save you countless hours and help you collaborate more effectively with your team.

This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy