Home > Software engineering >  Pass param to laravel 9 factory
Pass param to laravel 9 factory

Time:12-16

I need to seed DB with rows on different languages. For example, I have model Books with fields title, content and language_id. And model Languages with language info.

Schema::create('languages', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('code', 2);
    $table->timestamps();
});
Schema::create('books', function (Blueprint $table) {
    $table->id();
    $table->foreignId('language_id');
    $table->string('title');
    $table->text('content');
    $table->timestamps();

    $table->foreign('language_id')->references('id')->on('languages')->onUpdate('cascade')->onDelete('cascade');
});

I make BookFactory

class BookFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => fake()->sentence(rand(3, 7)),
            'content' => fake()->sentences(rand(5, 11))
        ];
    }
}

I can pass language param to fake() function, for example fake('de_DE'). How can I pass locale code (de_DE and etc.) to factory from seed?

class DatabaseSeeder extends Seeder
{
    public function run()
    {   
        \App\Models\Book::factory(10)->create();
    }
}

CodePudding user response:

You cannot pass the locale code from seeed to factory but you can create a state() if you want to make your factory dynamic :

class BookFactory extends Factory
{
    public function definition()
    {
        return [
            'title' => fake()->sentence(rand(3, 7)),
            'content' => fake()->sentences(rand(5, 11))
        ];
    }

    public function setLanguage(string $locale)
    {
        return $this->state(fn (array $attributes) => [
            'title' => fake($locale)->sentence(rand(3,7)),
            'content' => fake($locale)->realText(500), // you can use real text so that it will display a real text snippet.
        ])
    }
}

Then if you want to use it :

class DatabaseSeeder extends Seeder
{
    public function run()
    {   
        \App\Models\Book::factory(10)->setLanguage('de_DE')->create();
    }
}

CodePudding user response:

You can use below code snippet to resolve this issue Book::factory(10, ["locale" => 1])->create(); and get locale from factory by using states property $this->states[1]["locale"]

*) Kindly refer this doc https://laravel.com/docs/9.x/eloquent-factories#factory-states for implementation

  • Related