Laravel Database: Migrations, Seeders, Factories, and Rollbacks

Migrations

Migrations are like version control for your database, allowing you to modify your database structure in a consistent way.

Creating a migration:

bash
php artisan make:migration create_users_table

Example migration file:

php
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Running migrations:

bash
php artisan migrate

Seeders

Seeders populate your database with test data.

Creating a seeder:

bash
php artisan make:seeder UserSeeder

Example seeder:

php
public function run()
{
    DB::table('users')->insert([
        'name' => 'Admin User',
        'email' => 'admin@example.com',
        'password' => Hash::make('password'),
    ]);
}

Running seeders:

bash
php artisan db:seed
# Or for a specific seeder
php artisan db:seed --class=UserSeeder

Factories

Factories generate model instances with fake data, useful for testing and seeding.

Creating a factory:

bash
php artisan make:factory UserFactory --model=User

Example factory:

php
$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => bcrypt('password'),
    ];
});

Using factories:

php
// Create a single user
$user = factory(User::class)->create();

// Create multiple users
factory(User::class, 50)->create();

Rolling Back Migrations

Rollback the last migration:

bash
php artisan migrate:rollback

Rollback all migrations:

bash
php artisan migrate:reset

Rollback and re-run migrations:

bash
php artisan migrate:refresh

Rollback, re-run migrations, and seed:

bash
php artisan migrate:refresh --seed

Rollback a specific number of migrations:

bash
php artisan migrate:rollback --step=3

These tools together provide a powerful way to manage your database structure and data in Laravel applications.

To Top