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

cwray-tech's avatar

How to deal with deeply nested and interconnected relationships in Factories?

I'm building a pretty large application that has several interconnected models. Here are a few examples:

Teams

  • This is the Jetstream Teams model. Almost all other models belong to this model.

Orders

  • Customer Orders. Belongs to a customer and a team.

Customers

  • Belongs to a team
  • Has many orders

OrderItems

  • Belongs to an order.
  • Belongs to a product.

Products

  • Belongs to a team

So, I need to create an Order, that has many order items, and each order item product must be related to the same team as the order. Same with the customer relationship.

How would you set up a factory to seed this kind of relationship to ensure they all belong to the same team?

0 likes
6 replies
drewdan's avatar
drewdan
Best Answer
Level 15

Hello,

You can create factories with relationships, so choose the base model, make a factory for that, and then in the has, pass in the relationships it requires, and then, pass in the relationships that related model requires.

https://laravel.com/docs/8.x/database-testing#factory-relationships

Team::factory()->has(
    Customer::factory()->has(
        Order::factory()->has(
            OrderItems::factory()->has(Product::factory()))->count(20)
)->create()

Pretty sure there is a syntax error in there somewhere, but you should get the idea. You can do things like this.

1 like
cwray-tech's avatar

@drewdan Thank you. I have tried that.. The issue is that how do I ensure the Product is related to the same team as the customer/order?

drewdan's avatar

@cwray-tech I think you could do something like this

$user = User::factory()
            ->has(
                Post::factory()
                        ->count(3)
                        ->state(function (array $attributes, User $user) {
                            return ['user_type' => $user->type];
                        })
            )
            ->create();

Taken from the Laravel docs - https://laravel.com/docs/8.x/database-testing#factory-relationships - which suggests you can access the parents model you are creating and use it to change the state of the relationship factory, i,e assigning the team_id for the product

1 like
cwray-tech's avatar

@drewdan Thank you! I appreciate it. I will try this out and see if that works.

1 like

Please or to participate in this conversation.