How to integrate a custom faker provider in Laravel 8 factories

Published: Posted by Patrick Henninger

Factories are a conveniant way to easily generate data for our application for either testing or just general development purposes. Being able to quickly populate the database has benefits when developing big solutions too as it does allow to quickly adopt big changes to core data structures. However as the complexity of our application does increase in most cases the generators and data types already included with the faker library are fairly limited - a custom faker provider is required.

Usually we now would have to register your custom providers using a service provider, but this solution can get messy quite quickly. Luckily there is a more conveniant way to register our custom provider to faker since Laravel 8 intoduced dedicated factory classes for our eloquent models.

Looking at the new Factory base class provided by Illuminate/Database since version 8 we can find the new withFaker method which is responsible for the initialization and configuration of the faker instance being used by the factory. Overloading this method in our factory class will allow us to register our custom provider as shown in the following example:

use \Namespace\For\CustomProvider;

/**
 * @inheritDoc
 */
protected function withFaker()
{
    $faker = parent::withFaker();
    $faker->addProvider(new CustomProvider($faker));
    return $faker;
}

Now that our custom provider has been added to the faker instance of our model's factory class we can use it as we would use any other type provided by faker.

/**
 * Define the model's default state.
 *
 * @return array
 */
public function definition()
{
    return [
        ...
        'content' => $this->faker->customType(),
    ];
}