How to use 2 languages with Faker at the same time

241 Views Asked by At

Is it possible to instantiate two Faker instances with Laravel at the same time?

I want to have two fakers in a factory, one which generates english and another that generates french. They both have to be in the same factory because the database tables have english and french translations for each field.

The problem is when a new faker instance is created, the old Laravel faker's locale gets overwritten as well, making both generate French.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Model>
 */
class TestFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $faker = \Faker\Factory::create('fr_FR');
        // $faker->addProvider(new \Faker\Provider\fr_FR\Text($faker));
        return [
            'term_en' => $this->faker-> realText(200),
            'term_fr' => $faker-> realText(200),
        ];
    }
}

EDIT:

This actually works, I started the question using fakers words() provider which only generates latin.

EDIT #2:

There is something to be aware of, memory usage. This instantiates a faker instance every time the factory is used, this ends up slowing down mass seeding quite a bit.

0

There are 0 best solutions below