Introduction

In Laravel, Faker is often used to generate fake data in your factories and there in your tests, often there are times where more accurate “faked” data would improve your development experience. Extending faker by adding custom methods is as simple as binding them in a service provider. However, there are a couple of caveats. The fake helper resolves an instance of Faker using \Faker\Generator::class:en_US, where en_US is the locale set in your configuration files. The WithFaker trait for testing and the faker property of your factories will simply resolve \Faker\Generator::class. This article explains how to bind your extra service providers so that both have access to the new provider.

Creating a faker provider providers a class which extends \Faker\Provider\Base.

<?php

namespace App\Providers;

use Faker\Generator;
use Faker\Factory;
use Illuminate\Support\ServiceProvider;

class CustomFakerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Generator::class, function () {
            $faker = Factory::create();
            
            // Add your custom methods to the Faker instance
            $faker->addProvider(new CustomFakerProvider($faker));
            
            return $faker;
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

With this provider, you can now extend Faker’s capabilities with your own custom data generation methods. Let’s dive into creating a custom provider.

Creating A Custom Provider

To create a custom provider, you’ll need to extend the Faker\Provider\Base class and add your own methods for generating fake data. Here’s an example of a custom provider:

<?php

namespace App\Providers;

use Faker\Provider\Base;

class CustomFakerProvider extends Base
{
    /**
     * Generate a fake phone number with a custom format.
     *
     * @param string $format The format of the phone number.
     * @return string
     */
    public function customPhoneNumber($format = '###-###-####')
    {
        return $this->numerify($format);
    }

    // Add more custom methods here as needed
}

This custom provider adds a method customPhoneNumber() to Faker, allowing you to generate phone numbers with a custom format.

Binding the Custom Provider

Once you’ve created your custom provider, you need to bind it to the Faker instance in Laravel. To do this, you’ll use a service provider. Laravel’s service providers allow you to register bindings, providers, and more.

Here’s how you can bind your custom provider:

<?php

namespace App\Providers;

use Faker\Generator;
use Illuminate\Support\ServiceProvider;

class CustomFakerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Generator::class, function () {
            $faker = \Faker\Factory::create();

            // Add your custom provider to the Faker instance
            $faker->addProvider(new CustomFakerProvider($faker));

            return $faker;
        });
    }

    // Omitted: Bootstrapping services method
}

In this service provider, we’re binding our custom provider to the Faker instance so that it’s available throughout our Laravel application.

Using Custom Faker Data in Factories and Tests

Once your custom provider is bound, you can use your custom methods in your factories and tests. Here’s an example of how you might use the customPhoneNumber() method in a factory:

use App\Models\User;

$factory->define(User::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'phone' => $faker->customPhoneNumber(), // Using the custom method
    ];
});

And in your tests:

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    use RefreshDatabase;

    public function test_example()
    {
        $user = factory(User::class)->create([
            'phone' => $this->faker->customPhoneNumber(), // Using the custom method
        ]);

        // Your test assertions here
    }
}

By extending Faker, refining its capabilities with your custom data generation methods, you enhance your development experience.

Project inquiry form

Project Inquiry

The more information you provide, the better we’ll understand your project and find the right solutions for you. Or if you’d like to talk to a live person give us a call at 0161 241 54 53. Talk to you soon!

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.