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 🚀
1// You need to have User and Posts factories
2$user = User::factory()
3 // The User model has a hasMany "posts" relationship
4 ->hasPosts(3)
5 ->create();
6
7$posts = Post::factory()
8 ->count(3)
9 // The Post model has a belongsTo "user" relationship
10 // The array is optional. Use it to override an attribute if needed
11 ->forUser([
12 'name' => 'John Doe',
13 ]])
14 ->create();
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.