In Laravel, how do I retrieve a random user_id from the Users table for Model Factory seeding data generation?

Simon Suh picture Simon Suh · May 22, 2017 · Viewed 20.9k times · Source

Currently, in my ModelFactory.php, I have:

$factory->define(App\Reply::class, function (Faker\Generator $faker) {
  return [
    'thread_id' => 1,
    'user_id' => 1,
    'body' => $faker->paragraph
  ];
});

I would like to generate a random user_id from one of the user ID's already stored in the user table. I'm stumped because I don't know the way to display data output to code properly, and I was wondering how I would be able to allow Laravel to choose a random user ID and insert into the database. Thank you! :)

Answer

ayip picture ayip · May 22, 2017

Try the below.

use App\User; // Assuming this is your User Model class with namespace.

$factory->define(App\Reply::class, function (Faker\Generator $faker) {
  return [
    'thread_id' => 1,
    'user_id' => User::all()->random()->id,
    'body' => $faker->paragraph
  ];
});

Remember that this gets all the user data from your table and then choses an id randomly. So if your table has huge amount of data, it is not recommended. Instead, in your Test Case, you can create a new User (via its own factory) and assign the id to the Reply object generated from the above factory.

Alternately, you can query for a specific user in the above factory definition.

'user_id' => User::where('username', 'like', '[email protected]')->get()->random()->id

If you have a test user set up in your DB this will avoid pulling all the user data.