Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skiarsi's avatar

make faker's data from another table in factory

Hey guys I want to full table posts with some data in table users with faker. this is my code

	postsFactory.php : 
	$users = users::select('id')->get();
    return [
        'userId' => fake()->shuffle(array($users)),
        'postBody' => fake()->text(),
    ];

I want to get all user's Id from user table and save it to posts table in userId's column. I'm looking for something like this. [1,2,3,4,5,9,...]. It's not work. I did same thing in CI4 , but I can not do here, can anyone help me how to figure out this?

Tnx

0 likes
3 replies
vivekbansal's avatar

$varient = Varient::pluck('id')->toArray();

    return [
        'name' => fake()->imageUrl(),
        'varient_id' => fake()->randomElement($varient)
    ];
kevinbui's avatar

@skiarsi pls don't do that. Recycling is what you need.

Just define a PostFactory as usual:

return [
        'userId' => User::factory(),
        'postBody' => fake()->text(),
    ];

Then, when you create new posts, we can do:

Post::factory()
    ->recycle(User::all());
    ->count(3)
    ->create();

Does that answer your question? Let us know if you want something else.

Please or to participate in this conversation.