Laravel Faker Factory
- Faker ・・PHPライブラリ ダミーデータ生成
→Laravelには標準搭載
- Factory・・ダミーを量産する仕組み Laravel8からクラスベースに変更
日本語化対応
config/app.php
→'faker_locale' => ‘ja_JP’,
に変更
php artisan config:clear
でキャッシュ削除
php artisan make:factory ProductFactory —model=Product
php artisan make:factory StockFactory —model=Stock
—model=Product
で使用するモデルも紐付けて作成される
→UserFactoryというサンプルファイルはデフォルトではいってる
UserFactory
$model = User::class;
でUserモデルを使い、definitionで定義する
$this->faker->name(),
のようにfakerで用意されてるプロパティを使う
<?php namespace Database\Factories; use App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class UserFactory extends Factory { protected $model = User::class; public function definition() { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 'remember_token' => Str::random(10), ]; }
ProductFactory
-今回使うプロパティ
name
realText
numberBetween
'price' => $this->faker->numberBetween(10, 100000)
数字(指定した範囲)
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; class ProductFactory extends Factory { public function definition() { return [ //数値はSeeder側で定義した値にしないとエラーになる 'name' => $this->faker->name, 'information' => $this->faker->realText, 'price' => $this->faker->numberBetween(10, 100000), 'is_selling' => $this->faker->numberBetween(0,1), 'sort_order' => $this->faker->randomNumber, 'shop_id' => $this->faker->numberBetween(1,2), 'secondary_category_id' => $this->faker->numberBetween(1,6), //imageSeederで定義した範囲でないとエラーになる 'image1' => $this->faker->numberBetween(1,7), 'image2' => $this->faker->numberBetween(1,7), 'image3' => $this->faker->numberBetween(1,7), 'image4' => $this->faker->numberBetween(1,7), 'image5' => $this->faker->numberBetween(1,7), ]; } }
StockFactory
stockは外部キー制約でproduct_idをもっている
productfactoryで生成した内容と紐付ける
productfactoryから生成した順に登録される
<?php namespace Database\Factories; use App\Models\Product; use Illuminate\Database\Eloquent\Factories\Factory; class StockFactory extends Factory { public function definition() { return [ //stockは外部キー制約でproduct_idをもっている、productfactoryで生成した内容と紐付ける //productfactoryから生成した順に登録される 'product_id' => Product::factory(), 'type' => $this->faker->numberBetween(1,2), 'quantity' => $this->faker->randomNumber, ]; } }
※factoryとはログにでないので注意