Migration: lịch sử thay đổi database bằng code
Giống migration của Drizzle hay Prisma: mỗi thay đổi cấu trúc bảng là một file, ai kéo code về cũng chạy được giống nhau.
php artisan make:model Product -mfs # tạo model kèm migration (m), factory (f), seeder (s)
File migration trong database/migrations:
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->string('slug')->unique();
$table->unsignedInteger('price'); // giá VND, số nguyên
$table->text('description')->nullable();
$table->boolean('is_active')->default(true);
$table->timestamps(); // created_at, updated_at
});
}
public function down(): void
{
Schema::dropIfExists('products');
}
Các lệnh hay dùng:
php artisan migrate: chạy migration mới.php artisan migrate:status: xem đã chạy những gì.php artisan migrate:rollback: quay lui đợt gần nhất.php artisan migrate:fresh --seed: xóa sạch database, tạo lại và nạp dữ liệu mẫu. Chỉ dùng trên máy bạn.
Đã chạy migration trên server thì đừng sửa file đó nữa. Muốn đổi cột, tạo migration mới.
Đổi sang MySQL hoặc PostgreSQL
Mặc định là SQLite. Muốn đổi, sửa trong .env:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=hoc_laravel
DB_USERNAME=root
DB_PASSWORD=
rồi chạy lại php artisan migrate.
Factory: sinh dữ liệu giả
// database/factories/ProductFactory.php
public function definition(): array
{
$name = fake()->words(3, true);
return [
'category_id' => Category::factory(),
'name' => ucfirst($name),
'slug' => str($name)->slug(),
'price' => fake()->numberBetween(50, 500) * 1000,
'description' => fake()->sentence(),
];
}
Seeder: nạp dữ liệu mẫu
// database/seeders/DatabaseSeeder.php
public function run(): void
{
Product::factory(50)->create();
}
Chạy php artisan db:seed. Factory còn được dùng lại khi viết test (bài 12).
Bài tập
- Tạo model Category và Product kèm migration, factory, seeder.
- Viết migration cho hai bảng như ví dụ, chạy migrate.
- Viết factory cho cả hai, seeder tạo 5 danh mục, mỗi danh mục 10 sản phẩm.
- Chạy
php artisan migrate:fresh --seed, mở tinker đếm số sản phẩm.
Xem thêm
- 30 Days to Learn Laravel, Ep 10 - Model Factories (kênh Laracasts, tiếng Anh, 19 phút)
- Bài 10: Cấu hình Database & Tạo Table bằng Migration (kênh Hải Đăng Dev, tiếng Việt, 21 phút)