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()
{
AppModelsBook::factory(10)->create();
}
}
2
Answers
You can use below code snippet to resolve this issue:
and get locale from the factory by using states property:
Kindly refer to the Factory States doc for implementation
You cannot pass the locale code from seeed to factory but you can create a
state()
if you want to make your factory dynamic :Then if you want to use it :