Laravel: Two Ways to Seed Data with Relationships

While seeding data, it’s common to have one class for each database table. But what if there are relationships? I will show you two ways you can deal with it.

Imagine we have this simple database structure – database contacts and contact_companies (taken from our Contact Management module in QuickAdminPanel):

contact management laravel

How to seed data in both tables?
Of course, we will use Faker library, but still – there are a few ways to implement it.

First, let’s define our factories.


And database/factories/ContactFactory.php:

Now, as you can see, there’s no contacts.company_id defined. Here’s where we have a few options:

Version 1. Create contacts inside of company seed

Let’s create a company seeder:

And then fill the file database/seeds/CompanySeed.php with this:

Basically, we’re creating 10 companies, and for each of them we’re creating one contact, using Eloquent relationship in app/ContactCompany.php:

Version 2. Create company along with the contact

The other way around would be to use seed for Contacts.

And then add only this line in database/seeds/ContactSeed.php:

You’re probably wondering where the relationship would come from? We can create a “parent” entry directly in the factory! Like this:


See the first field? We’re using parent factory and creating a company “on-the-fly”.

That’s it, isn’t it simple?
In official Laravel documentation you can find more information about seeding and using factories with Faker.

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

9 thoughts on “Laravel: Two Ways to Seed Data with Relationships

      1. hello please do you have any articles on image resizing in laravel? maybe using cloudinary api or so. i’m trying to resize all images uploaded by users of my site to the same size.

  1. These approaches will only bring you so far. Any other approach, for complicated database designs? E.g. multiple relationships either way.

Leave a Reply

Your email address will not be published. Required fields are marked *