Summer Sale! All accounts are 50% off this week.

normykinz's avatar

Faker Provider and the fake() Helper

Heelo peeps!

I've created a custom Faker provider for generating random enum cases, using this tutorial.

https://hofmannsven.com/2021/faker-provider-in-laravel

This works beautifully when using $this->faker->enum(EnumType::class) in a factory. But now when using the fake() helper. It's a minor problem but I wonder if anybody could give me a pointer or two on how to get the helper to use the faker generator returned from the service provider.

0 likes
2 replies
normykinz's avatar
normykinz
OP
Best Answer
Level 4

The turoeial I was using is a bit out of date but I managed to solve things after a bit of Googling.

<?php

namespace App\Providers;

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

class FakerServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $locale ??= app('config')->get('app.faker_locale') ?? 'en_US';
        $abstract = Generator::class.':'.$locale;

        $this->app->afterResolving($abstract, function (Generator $instance) {
            $instance->addProvider(new EnumProvider($instance));
        });
    }

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

Please or to participate in this conversation.