Read this section of the docs. https://laravel.com/docs/10.x/eloquent-factories#defining-relationships-within-factories
How to go about seeding foreign keys?
Hello, I'm a complete beginner to Laravel and I'm attempting to use seeders to seed a database I'm using for a test project of an inventory management system. However, I run into issues when I attempt to seed tables that have foreign keys. I get errors such as: General error: 1364 Field 'category_id' doesn't have a default value"
Of course, I get that this is because the key needs to have a value, but since this is dummy data, I'm not quite sure of how to go about adding foreign keys. I'm using faker to generate random values for the rest of the attributes and I didn't run into any issues with that, it's just the foreign keys that are giving me a headache.
This is the relevant code I'm using if it helps:
ProductFactory
public function definition(): array
{
return [
'name' => $this->faker->word(),
'description' => $this->faker->sentence(),
'base_price' => $this->faker->randomFloat(4),
'base_cost' => $this->faker->randomFloat(4)
];
}
ProductSeeder
public function run(): void
{
Product::factory()->count(10)->create();
}
Please or to participate in this conversation.