skip to Main Content

I am new to Laravel and here is my setup:

  • I have a companies table which is linked to a plans 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 the Plan 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


  1. Chosen as BEST ANSWER

    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 custom PlanSeeder to isolate the Plan creation and it now works perfectly!

    Thanks to everyone who took the time to answer :).


  2. You could manually select a plan_id from the existing plans without using the fake() function.

    $existingPlanIds = Plan::pluck('id')->toArray();
    
    return [
        'plan_id' => $this->faker->randomElement($existingPlanIds),
        'name' => $this->faker->company(),
        'plan_status' => $this->faker->randomElement(['active', 'pending', 'canceled']),
    ];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search