LaravelのFakerを拡張する

2015年8月25日火曜日
  • このエントリーをはてなブックマークに追加

DatabaseServiceProviderを継承したプロバイダを作成する

$ php artisan make:provider DatabaseServiceProvider

App\Providers\DatabaseServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Database\DatabaseServiceProvider as BaseDatabaseServiceProvider;
use Faker\Factory as FakerFactory;
use Faker\Generator as FakerGenerator;
use Illuminate\Database\Eloquent\Factory as EloquentFactory;

class DatabaseServiceProvider extends BaseDatabaseServiceProvider
{
    /**
     * Register the Eloquent factory instance in the container.
     *
     * @return void
     */
    protected function registerEloquentFactory()
    {
        $this->app->singleton(FakerGenerator::class, function () {
            return FakerFactory::create(config('app.faker_locale'));
        });

        $this->app->singleton(EloquentFactory::class, function ($app) {
            $faker = $app->make(FakerGenerator::class);
            $faker->addProvider(new Faker\FakerProvider($faker));

            return EloquentFactory::construct($faker, database_path('factories'));
        });
    }

}

app.php

   'faker_locale' => 'ja_JP',
   'providers' => [
   // Illuminate\Database\DatabaseServiceProvider::class,
   App\Providers\DatabaseServiceProvider::class,
   ];

App\Providers\Faker\FakerProvider.php

<?php

namespace App\Providers\Faker;

use Faker\Provider\Base;

class FakerProvider extends Base
{
    // 拡張したいものを定義
}

ラベル: ,


0 件のコメント:

コメントを投稿