Mẫu tạo dữ liệu Product với seeder (ok)

C:\xampp\htdocs\bangtaivietnam\database\factories\ProductFactory.php

<?php
namespace Database\Factories;
use App\Models\Product;
use Illuminate\Database\Eloquent\Factories\Factory;
class ProductFactory extends Factory {
  protected $model = Product::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'product_name'    => $this->faker->text(10),
    ];
  }
}

C:\xampp\htdocs\bangtaivietnam\database\seeders\ProductSeeder.php

<?php
namespace Database\Seeders;
use App\Models\Product;
use Illuminate\Database\Seeder;
class ProductSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Product::factory()->count(100)->create();
  }
}

C:\xampp\htdocs\bangtaivietnam\database\migrations\2022_06_18_203456_create_table_products_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTableProductsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('products', function (Blueprint $table) {
      $table->id();
      $table->string('product_name');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('products');
  }
}

C:\xampp\htdocs\bangtaivietnam\app\Http\Controllers\ProductController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller {
  //
}

C:\xampp\htdocs\bangtaivietnam\app\Models\Product.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model {
  use HasFactory;
}
php artisan db:seed ProductSeeder

Last updated