Blog Post

How to seed Many-to-Many Relationships in Laravel + Eloquent

Have you ever wondered how to seed many-to-many relationships in Laravel? In this example, we'll show how to achieve this using Orders and Products.

Let's pretend you have a database with Orders and Items (Products), maybe similar to this:

Schema::create('orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->decimal('total');
            $table->unsignedBigInteger('user_id');

            $table->timestamps();
        });

Schema::create('items', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->decimal('price');
            $table->text('name');

            $table->timestamps();
        });

Schema::create('item_order', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedInteger('order_id');
            $table->unsignedInteger('item_id');

            $table->timestamps();
        });

Now, let's define the models:

and, of course, products - let's call them items:

Based on the Many-to-Many relationship between these two models, Laravel will automatically use our pivot table item_order for us.

So far so good - But how do we seed Orders with Items attached to our database?

Here you go (Don't forget to create your corrosponding factory classes - not shown here.)

Seed & Enjoy!

php artisan db:seed   

Read more about seeding here:

https://laravel.com/docs/9.x/seeding