How to implement your own Faker provider in Laravel

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

Where can I save a custom provider in my application and how to use it?

+7
php laravel faker laravel-seeding
source share
2 answers

You must use php artisan to create a custom provider ...

At the command prompt, navigate to the root of your application and type ...

 php artisan make:provider FakerServiceProvider 

This should create a new provider in the app/Providers folder. Here's what my register function looks like, for example, with the faker file.

 /** * Register the application services. * * @return void */ public function register() { $this->app->singleton('Faker', function($app) { $faker = \Faker\Factory::create(); $newClass = new class($faker) extends \Faker\Provider\Base { public function title($nbWords = 5) { $sentence = $this->generator->sentence($nbWords); return substr($sentence, 0, strlen($sentence) - 1); } }; $faker->addProvider($newClass); return $faker; }); } 

I am using an anonymous class here. If you have php <7, you will most likely need to create a new file with a new provider class and pass it. Make sure you also add this new provider to your providers array in app/config.php .

Now that it is registered, you can grab your new faker class using the following ...

 $faker = app('Faker'); echo $faker->title; 

In addition, if you look at the documents at https://laravel.com/docs/5.2/facades , you can also easily make a Faker facade. All the heavy lifting is done, you just need to create a new facade class, getFacadeAccessor return 'Faker' and add it to the facades array in app/config.php .

Then you can just use it like that ...

 echo Faker::title; 
+9
source share

Create your own provider class and save it in the /Faker/CustomProvider.php application. The code:

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

Then you just need to add your custom provider for selection using the addProvider method. An example of a laravel factory with the addition of a custom provider:

 <?php use Faker\Generator as Faker; $factory->define(App\Models\Model::class, function(Faker $faker) { $faker->addProvider(new App\Faker\CustomProvider($faker)); return [ 'name' => $faker->customName, ]; }); 
0
source share

All Articles