Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Faker Locale in Laravel 5.2

Tags:

php

laravel

Is there a way to specify the Faker locale in the database/factories/ModelFactory.php file ? Here is my non functioning attempt at doing so >,<

$factory->define(App\Flyer::class, function (Faker\Generator $faker) {

    // What is the correct way of doing this?
    $faker->locale('en_GB'); 

    return [
        'zip' => $faker->postcode,
        'state' => $faker->state,  
    ];
});

Thanks for reading!

like image 543
David Kerr Avatar asked Dec 28 '15 16:12

David Kerr


2 Answers

Faker locale can be configured in the config/app.php configuration file. Just add the key faker_locale.

e.g.: 'faker_locale' => 'fr_FR',

See also my PR to document that previously undocumented feature: https://github.com/laravel/laravel/pull/4161

like image 151
Vincent Mimoun-Prat Avatar answered Nov 10 '22 05:11

Vincent Mimoun-Prat


THIS ANSWER IS ONLY VALID FOR LARAVEL <=5.1 OR WHEN YOU WANT TO USE MANY DIFFERENT LOCALES see this answer for a solution in Laravel >=5.2.

To use a locale with Faker, the generator needs creating with the locale.

$faker = Faker\Factory::create('fr_FR'); // create a French faker

From the faker documentation:

If no localized provider is found, the factory fallbacks to the default locale (en_EN).

Laravel by default, binds the creation of a faker instance in the EloquentServiceProvider. The exact code used to bind is:

// FakerFactory is aliased to Faker\Factory
$this->app->singleton(FakerGenerator::class, function () {
    return FakerFactory::create();
});

It would appear that Laravel has no way to modify the locale of the faker instance it passes into the factory closures as it does not pass in any arguments to Faker.

As such you would be better served by using your own instance of Faker in the factory method.

$localisedFaker = Faker\Factory::create("fr_FR");

$factory->define(App\Flyer::class, function (Faker\Generator $faker) {

    // Now use the localisedFaker instead of the Faker\Generator
    // passed in to the closure.
    return [
        'zip' => $localisedFaker->postcode,
        'state' => $localisedFaker->state,  
    ];
});
like image 24
David Barker Avatar answered Nov 10 '22 06:11

David Barker