laravel model factory seed generate from existing

Viewed 5172

I am trying to seed a table with a foreign key and I'm stuck on how I would tell the model to randomly pull values from what already exists.

ModelFactory

$factory->define(App\Vendor::class, function(Faker\Generator $faker) {
    return [
        'name' => $faker->company,
    ];
});

$factory->define(App\Device::class, function(Faker\Generator $faker) {
    return [
        'vendor' => ,
        'name' => $faker->company,
        'mac_address' => $faker->macAddress,
    ];
});

Seeds

VendorTableSeeder

public function run()
{
    factory(App\Vendor::class, 150)->create();
}

DeviceTableSeeder

public function run()
{
    factory(App\Device::class, 50)->create();
}

DataSeeder

$this->call(VendorTableSeeder::class);
$this->call(DeviceTableSeeder::class);

I seed the Vendor table before the Device table and would like to populate a random vendor id from the existing vendors.

'vendor' => 'factory::App\Vendor'

But I am getting

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: foreign key constraint fails

It looks like the insert is trying to insert factory::App\Vendor as a string for the vendor column. I am trying to figure out how to have it pull from the existing vendors.

3 Answers

Here is simple way to generator factory using random() method

$factory->define(App\Device::class, function(Faker\Generator $faker) {
    return [
        // another way to, Get any random row from existing records
        'vendor_id' => App\Vendor::all()->random()->user_id,
        'name'        => $faker->company,
        'mac_address' => $faker->macAddress,
    ];
});
Related