I’m trying to seed random belongsTo relationships for a Post
, but they are all just being created with the same User
and Community
.
Code:
$users = AppModelsUser::factory(100)
->create();
$communities = AppModelsCommunity::factory(10)
->create();
AppModelsPost::factory()
->for($users->random()->first())
->for($communities->random()->first())
->create();
After seeding, when I look at the database, the user_id
and community_id
is 1
for all of the posts.
How do I make it random for each seeded post based on the users and communities created beforehand?
Tried using random()
but does not seem to take effect.
3
Answers
I figured it out by using
recycle
method in the seeder and specifying a an id for each relationship in the factory.PostFactory
:New seeder code:
Works great now :D
Here is your asked answer in detail https://onenetly.com/question/laravel-use-randomly-created-factory-for-relation/
You can use a closure within a Sequence to generate random
user_id
andcommunity_id
for eachpost
. For example:In case your code is exactly the same as the one you have provided, it is better to place the
User
andCommunity
creation directly in the post factory.