Langkah ini akan mempersiapkan database dan migrasi yang dibutuhkan untuk fitur manajemen produk pada e-commerce Anda.
1. Buat Model dan Migrasi Produk
Jalankan perintah berikut untuk membuat model dan file migrasi untuk produk:
php artisan make:model Product -m
Perintah ini akan membuat:
- Model:
app/Models/Product.php - Migrasi:
database/migrations/xxxx_xx_xx_create_products_table.php
2. Tambahkan Kolom di File Migrasi
Edit file migrasi di database/migrations/xxxx_xx_xx_create_products_table.php dan tambahkan struktur tabel produk. Contoh:
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('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->text('description')->nullable();
$table->decimal('price', 10, 2);
$table->integer('stock')->default(0);
$table->string('image')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('products');
}
};
3.3. Jalankan Migrasi
Setelah migrasi diperbarui, jalankan perintah ini untuk membuat tabel di database:
php artisan migrate
4. Tambahkan Relasi (Opsional)
Jika produk memiliki kategori atau tag, Anda bisa membuat tabel tambahan da relasi. Contoh untuk kategori:
Buat model dan migrasi untuk kategori:
php artisan make:model Category -m
Tambahkan kolom di file migrasi create_categories_table.php:
public function up(): void
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->string('image')->nullable();
$table->timestamps();
});
}
Hubungkan produk dengan kategori di model Product:
public function category()
{
return $this->belongsTo(Category::class);
}
5. Seeder untuk Produk (Opsional)
Untuk data dummy, buat seeder:
php artisan make:seeder ProductSeeder
Tambahkan data di database/seeders/ProductSeeder.php:
use App\Models\Product;
public function run(): void
{
Product::create([
'name' => 'Sample Product',
'slug' => 'sample-product',
'description' => 'This is a sample product.',
'price' => 100.00,
'stock' => 50,
'image' => 'sample.jpg',
]);
}
Jalankan seeder:
php artisan db:seed --class=ProductSeeder
Setelah itu, database dan data product akan otomatis insert di tabel.