独学者Fossa

独学していることなど

簡易モジュール構造(3)

使用環境

Name Version
PHP 8.1.7
Laravel 9.17.0

Using Model Factories

今回、Module構造の中で、Database/Factoriesを使って、Seedingしたいと思います。

Modules\Todo\Models\Todo

<?php

namespace Modules\Todo\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Todo extends Model
{
    use HasFactory;

    protected $table = 'todos';

    protected static function newFactory()
    {
        return \Modules\Todo\Database\Factories\TodoFactory::new();
    }
}

ポイントは、2つです。

  • use HasFactory
  • newFactory()

Modules\Todo\Database\Factories\TodoFactory

<?php

namespace Modules\Todo\Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class TodoFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = \Modules\Todo\Models\Todo::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
                       <省略>
        ];
    }
}

Modules\Todo\Database\Seeders\TodosTableSeeder

<?php

namespace Modules\Todo\Database\Seeders;

use Illuminate\Database\Seeder;
use Modules\Todo\Models\Todo;

class TodosTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Todo::factory(20)->create();
    }
}

Modules\Todo\Database\Seeders\TodoDatabaseSeeder

<?php

namespace Modules\Todo\Database\Seeders;

use Illuminate\Database\Seeder;

class TodoDatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->call([
            TodosTableSeeder::class,
        ]);
    }
}

Database/Factoriesを使わない方法

<?php

namespace Modules\Todo\Database\Seeders;

use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
use Modules\Todo\Models\Todo;

class TodosTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        $faker = Faker::create();

        for($i = 1 ; $i <= 10 ; $i++){
            Todo::create([
         <省略>
            ]);
        }
    }
}