Search code examples
phpmysqllaraveleloquentfactories

how do I create a laravel factory that references another models mysql table?


I am trying to create a factory for a "posts" model

I need the community_id field filled with random selections from the communities table in the id column. I also need to fill the user_id field with random selections from the communities table in the id column.

Can you please help me with how to code this?

Thanks in advance!


Solution

  • I was able to come up with an answer and it is the following:

        public function definition()
        {
            $userIDs = DB::table('users')->pluck('id');
            return [
                'user_id' => $faker->randomElement($userIDs),
                'name' => fake()->sentence(),
                'description' => fake()->sentence(),
            ];
        }
    

    Using DB::table('users')->pluck('id') allows us to use the DB facade provided by Laravel to reference the users table and pluck the id column.

    We are then saving this array of results in a $userIds variable which we then use in the return inside the definition() method, where in the 'user_id' key value pair we call $faker->randomElement($userIds) which is a helper function that will select a random item from an array of values passed to it, which in this case we have passed an array of the user ids.

    I hope this solution helps those who might need assistance in the future with this problem.