94 words, 1 min read

We use factories a lot. Did you know about the "for[Relation]" and "has[Relation]" magic methods? You just need to make sure you have the relationship set up in your model and you are good to go πŸš€

// You need to have User and Posts factories
$user = User::factory()
// The User model has a hasMany "posts" relationship
->hasPosts(3)
->create();
$posts = Post::factory()
->count(3)
// The Post model has a belongsTo "user" relationship
// The array is optional. Use it to override an attribute if needed
->forUser([
'name' => 'John Doe',
]])
->create();

source