How to implement your own Faker provider in Laravel

后端 未结 3 1564
独厮守ぢ
独厮守ぢ 2021-02-07 08:50

I want to create a custom provider for Faker in Laravel (e.g. one for a random building name).

Where do I store the custom provider in my application and how do I use i

3条回答
  •  生来不讨喜
    2021-02-07 09:04

    Create your custom provider class and save it under app/Faker/CustomProvider.php. Code:

    namespace App\Faker;
    
    use Faker\Provider\Base;
    
    class CustomProvider extends Base
    {
        public function customName()
        {
            return $this->generator->sentence(rand(2, 6));
        }
    }
    

    Then you need just add your custom provider to faker by addProvider method. Example of laravel's factory with adding custom provider:

    define(App\Models\Model::class, function(Faker $faker) {
        $faker->addProvider(new App\Faker\CustomProvider($faker));
    
        return [
             'name' => $faker->customName,
        ];
    });
    

提交回复
热议问题