How to use factories to create relationships which follow a sequence
Factories an extremely useful tool for testing. The more complex the use case, the more awesome you find out Laravel factories are.
For instance, we might need to create a few items, each one with a different measurement of its own:
```php
Item::factory()
//...
->has(Measurement::factory()->state(new Sequence(
['length' => 50, "width" => 110],
['length' => 65, "width" => 200],
['length' => 190, "width" => 295],
)))
->count(3)
->create()
```
This will result in 3 items, each item having one unique measurement assigned. The first item will have a measurement with values corresponding to the first array in the sequence and so on.
Denisa Halmaghi
08 Dec 2021
« Back to post