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

heizenberg's avatar

Laravel ModelFactory Seeding Pivot Table

Hi, I need help on how to seed many-to-many relationship using ModelFactory in Laravel. In my ModelFactory, I have the default factory of user and here are the products and cart factory:

ModelFactory

$factory->define(App\Product::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'image' => $faker->imageUrl(600, 480),
        'price' => $faker->randomFloat(2, 100, 500)
    ];
});

$factory->define(App\Cart::class, function (Faker\Generator $faker) {
    return [
        'user_id' => App\User::lists('id');
    ];
});

and then I have this in my DatabaseSeeder

public function run()
    {
        App\User::truncate();
        App\Cart::truncate();
        App\Product::truncate();

        DB::table('cart_product')->truncate();

        factory(App\Product::class, 10)->create();
        factory(App\User::class, 10)->create()->each(function($u)
        {
            $u->cart()->save(factory(App\Cart::class)->create()->each(function($c)
            {
                $ids = App\Product::lists('id')->toArray();
                $c->products()->sync($ids);
            }));
        });
    }

Here are my models relationships: User

public function cart()
{
    return $this->hasOne(Cart::class);
}

Cart

public function user()
{
    return $this->belongsTo(User::class);
}

public function products()
{
    return $this->belongsToMany(Product::class);
}

Here are my tables:

carts

id
user_id

cart_product

id
cart_id
product_id
quantity

When I run php artisan db:seed I'am getting this error

[Symfony\Component\Debug\Exception\FatalThrowableError]

  Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, boo
lean
  given, called in ...\...\...\...\Cashier\database\seeds\DatabaseSeeder.php on line 27
0 likes
0 replies

Please or to participate in this conversation.