laracoft's avatar

Factory from a relation

Is there a way to chain from a relation to a factory? e.g.

$user->posts()->factory()->count(3)->create()
0 likes
6 replies
tykus's avatar
tykus
Best Answer
Level 104

What is the context here - do you use the User Factory to create the $user? If yes, then you can create the posts using the magic hasXXX method:

User::factory()->hasPosts(3)->create([/* attributes */])
laracoft's avatar

I would like the user to have specific data, so created it using a normal User::create(...), then I want to link it to a bunch of posts but don't want to write verbose code.

tykus's avatar

@laracoft right... and why can't you do that; create takes an array of attributes.

laracoft's avatar

@tykus

I tried, but got this

BadMethodCallException: Call to undefined method App\Models\User::hasPosts()
laracoft's avatar

@tykus

I suppose you meant User::factory()->hasPost(3)->create([...])?

Please or to participate in this conversation.