Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zagreus's avatar

Factory Issue

I'm trying to generate factories for my models, however it's not quite working as I would expect.

Here is my factory:

$factory->define(SubscriptionPlan::class, function (Faker\Generator $faker) {

    return [
        'name' => $faker->word,
        'description' => $faker->paragraph,
        'interval' => $faker->randomElement([SubscriptionPlan::INTERVAL_NONE, SubscriptionPlan::INTERVAL_MONTHLY, SubscriptionPlan::INTERVAL_WEEKLY]),
        'price' => $faker->numberBetween(100,10000),
        'stripe_id' => $faker->uuid,
        'account_id' => Account::all()->random()->id,
        'role_id' => Role::all()->random()->id,

    ];
});

Here is my seeder:

        factory(Account::class, 100)->create()->each(function($account) {
            $account->subscriptionPlans()->save(factory(App\SubscriptionPlan::class, 5)->make());
        });

When I run without trying to create the subscription plan then it works to create the accounts, however when I add the subscription plan line in I get this error:

[Symfony\Component\Debug\Exception\FatalThrowableError] Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::s ave() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate \Database\Eloquent\Collection given, called in C:\Users\Documents\app database\seeds\AccountSeeder.php on line 16

Any help would be much appreciated.

0 likes
4 replies
zagreus's avatar

@ModestasV - Tried that, unfortunately I get the same error.

@Gator - I changed the command to

$account->subscriptionPlans()->create(factory(App\SubscriptionPlan::class, 5));

which I think is what you mean. I get a different error - Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::c reate() must be of the type array, object given, called in C:\Users\Documents\app\database\seeds\AccountSeeder.php on line 16

zagreus's avatar
zagreus
OP
Best Answer
Level 3

I worked out the issue - it was because I was calling the factory multiple times. I will need to put it in a for loop to get multiple records:

for ($i=0; $i < 5; $i++) { 
    $account->subscriptionPlans()->save(factory(Trainerous\SubscriptionPlan::class)->make());   
            }

Please or to participate in this conversation.