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) {


Schema::create('items', function (Blueprint $table) {


Schema::create('item_order', function (Blueprint $table) {


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:

We'll Call You Back