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:
php artisan make:migration create_users_table
Example migration file:
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:
php artisan migrate
Seeders
Seeders populate your database with test data.
Creating a seeder:
php artisan make:seeder UserSeeder
Example seeder:
public function run() { DB::table('users')->insert([ 'name' => 'Admin User', 'email' => 'admin@example.com', 'password' => Hash::make('password'), ]); }
Running seeders:
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:
php artisan make:factory UserFactory --model=User
Example factory:
$factory->define(User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => bcrypt('password'), ]; });
Using factories:
// Create a single user $user = factory(User::class)->create(); // Create multiple users factory(User::class, 50)->create();
Rolling Back Migrations
Rollback the last migration:
php artisan migrate:rollback
Rollback all migrations:
php artisan migrate:reset
Rollback and re-run migrations:
php artisan migrate:refresh
Rollback, re-run migrations, and seed:
php artisan migrate:refresh --seed
Rollback a specific number of migrations:
php artisan migrate:rollback --step=3
These tools together provide a powerful way to manage your database structure and data in Laravel applications.