Search code examples
phpmysqllaravel-5multilingual

conditional multi-lingual laravel seeder


Suppose I have a table that contains a set of data in multiple languages and a foreign key lang_code referencing to the code on language table.

now I have to seed data table based on lang_code (en, es). How do I make conditional seeder to seed based upon the foreign key value being assigned, i.e. if the lang_code is en then seeds in English and so on?

here is what I have on the dataTableSeeder

public function run(Faker $faker)
{
    $fakerEs = Faker\Factory::create('es_ES');
    $instructionIDs = DB::table('oes_instructions')->pluck('id')->toArray();;
    $languageIDs = DB::table('oes_languages')->pluck('code')->toArray();;

    foreach (range(1,4) as $index) {
        DB::table('oes_exam_instructions_data')->insert([
        'instruction_id' => $faker->randomElement($instructionIDs),
        'locale' => $faker->randomElement($languageIDs), 
        'content' => $faker->paragraphs(10, $asText = true),   
        //Here ho do i make this based on $languageIDs => $faker->paragraphs(10, $asText = true) 
        'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
        'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
        ]);
    }
}

Solution

  • okay was simple but i think it would be easier using Model Factory.

    $fakerEs = Faker\Factory::create('es_ES');
        $instructionIDs = DB::table('oes_instructions')->pluck('id')->toArray();
        $languageIDs = DB::table('oes_languages')->pluck('code')->toArray();
    
        foreach ($instructionIDs as $instructionID) {
            foreach ($languageIDs as $languageID) {
                $data = ($languageID == 'en') ? $faker->paragraphs(6, $asText = true) : $fakerEs->paragraphs(6, $asText = true);
                DB::table('oes_instructions_data')->insert([
                'instruction_id' => $instructionID,
                'locale' => $languageID,
                'content' => $data,
                'created_at' => Carbon::now()->format('Y-m-d H:i:s'),
                'updated_at' => Carbon::now()->format('Y-m-d H:i:s')
                ]);
            }
        }