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

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! :)



Solution 1:[1]

Any class that extends Illuminate\Database\Eloquent\Model will be able to do this:

User::inRandomOrder()->first()

Or to get a Collection of 3 items:

User::inRandomOrder()->limit(3)->get()

This might be more efficient than using User::all()->first(), which ought to first query all Users.

Your IDE (like PhpStorm) will probably be wildly confused that this is an option though.

Also see: Laravel - Eloquent or Fluent random row

Solution 2:[2]

It does not work like that 'user_id':

User::all()->random()->user_id

But that's how it works:

User::all()->random()->id

Solution 3:[3]

It may not be that efficient but you can use it:

User::all('id')->random();

or

rand(1,User::count());

or

User::inRandomOrder()->limit(1)->get();

First one will be more faster than User::all()->random()->id; because that all function by default gets '*' as column name parameter. So, it will get all the columns for all the rows.

Solution 4:[4]

I personally like to use.

App\User::pluck('id')->random()

Change the model name which model you want

Solution 5:[5]

If Anyone wants a unique User_id you can try this.

'user_id' => User::all()->unique()->random()->id,

Or either it's

'user_id' => User::all()->random()->id,

Model name can change as your wants.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 Pranta Saha
Solution 5 Md Atiqur