Using factories with more than one relationship

Sometimes you can't follow the typical naming convention

Joel Clermont
Joel Clermont

Laravel factories are a simple and clean way of setting up data in your tests. They really shine when you need to create models with relationships.

Instead of multiple interim steps to create separate models and then link them together, you can use the for() helper to do it one expressive statement.

$user = User::factory()->create();

$client = Client::factory()->for($user)->create([
    'name' => 'Tires and More',

This helper uses naming conventions to know that our $user, which is an instance of the User model, is going to be set on the user() relation of our Client model.

But users are a great example of data that can be used multiple ways. For example, maybe one user is the owner of a client, and a different user is a distributor for that client.

Can we still use the for() helper? How would it know what relationship to set? Laravel has us covered.

$owner = User::factory()->create();
$distributor = User::factory()->asDistributor()->create();

$client = Client::factory()->for($user)->for($distributor, 'distributor')->create([
    'name' => 'Tires and More',

By passing a second parameter to the for() helper, I can tell Laravel which relationship to set, since we can't rely on the naming convention in this particular case.

Here to help,


P.S. Testing not only helps you catch bugs, but it can help you design better structure in your code. If you feel unsure on how to introduce testing to your Laravel app, we can help!

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.