I am new to Laravel and here is my setup:
- I have a
companies
table which is linked to aplans
table (plan_id
) - I have a function that seed the
plans
table with very specific data - I have created a factory for the
Company
model but not for thePlan
model as I don’t want random data for this model (I have 3 plans with prices)
My issue is that when I run the Company
factory, it creates new Plan
entries instead of using the existing ones.
Here is my DatabaseSeeder
:
/**
* Seed the application's database.
*/
public function run(): void
{
// Create the plans.
$this->createPlans();
Company::factory()
->count(3)
->create();
}
/**
* Create the plans.
*
* @return void
*/
private function createPlans(): void
{
Plan::create([
'name' => __('Free'),
'amount' => 0.00,
]);
Plan::create([
'name' => __('Pro'),
'amount' => 99.95,
]);
Plan::create([
'name' => __('Business'),
'amount' => 199.95,
]);
}
And my CompanyFactory
:
public function definition(): array
{
return [
'plan_id' => fake()->randomElement(Plan::all()->pluck('id')->toArray()),
'name' => fake()->company(),
'plan_status' => fake()->randomElement(['active', 'pending', 'canceled']),
];
}
Each time I seed the database, it creates x new entries for the plans instead of using existing entries. I have tried many things, but I can’t get it to work… Could somebody point me in the right direction?
2
Answers
Ok I have found my issue. I was running the
db:seed --class=DatabaseSeeder
command so it makes sense that it creates everytime 3 new entries as this what I've written... So I have created a customPlanSeeder
to isolate thePlan
creation and it now works perfectly!Thanks to everyone who took the time to answer :).
You could manually select a plan_id from the existing plans without using the fake() function.