3

I am trying to create seeders for testing purposes. I have users that belongs to a room via a room id, these rooms are created via a room seeder, in my users seeder, I create a user and update the room_id attribute like this,

factory(App\User::class, 150)->create([
        'host' => false,
        'room_id' =>  App\Room::inRandomOrder()->first()->id
    ]);

My problem is that all users generated here, all get the same room id, how can a truly get a random room id from the database and use it in my seeder?

Udders
  • 6,914
  • 24
  • 102
  • 194
  • App\Room::all()->random()->id Duplicate? https://stackoverflow.com/questions/13917558/laravel-eloquent-or-fluent-random-row – Big A Oct 15 '19 at 10:39
  • You can use [rand](https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_rand) to get a random id from the db. – Andrei Oct 15 '19 at 10:39
  • @BigA not asking how to get random, I am asking why my random is not random but assiging the same ID to every user that is created, even though it has 30+ IDS to choose from. – Udders Oct 15 '19 at 10:44

4 Answers4

1

I had the same problem with seeding. The problem is that, you are overriding the factory's default model attributes by passing an array of "values". You are passing the value of App\Room::inRandomOrder()->first()->id to the create method. So you would have all users with the same room_id.

To solve this issue, in laravel 8, you can move the 'room_id' => Room::inRandomOrder()->first()->id to your UsersFactory definition:

class UsersFactory {
...

    public function definition()
    {
        return [
            'room_id' => Room::inRandomOrder()->first()->id
        ];
    }
...
}

And create users like this,

App\User::factory()->count(150)->create([
    'host' => false
]);

In older version of laravel, define your factory as below:

$factory->define(App\User::class, function ($faker) use ($factory)  {
    return [
        'room_id' => Room::inRandomOrder()->first()->id
    ];
});

And create users like this,

factory(App\User::class, 150)->create([
        'host' => false,
    ]);

amrezzd
  • 1,787
  • 15
  • 38
0

Try:

App\Room::all()->random()->id
Johannn
  • 138
  • 7
0
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    $users = factory(\App\User::class, 150)->create([
        'host' => false,
        'room_id' => $this->getRandomRoomId()
    ]);
}

private function getRandomRoomId() {
    $room = \App\Room::inRandomOrder()->first();
    return $room->id;
}

Try this one. It works for me. Hopefully it works for you.

0

Try this one. Also, make sure that you have multiple auto incremented room entries in the room table.

$factory->define(App\User::class, function ($faker) use ($factory)  {
    return [
        'host' => false,
        'room_id' => $factory->create(App\Room::class)->id
    ];
});