Search code examples
phplaravel-5.5fakerlaravel-seeding

Set other columns to same type depending on a column value set - Laravel Faker


I'm using Faker in my Laravel 5.5 project to fake some data. I ran into this issue where I need to set two other columns inside the faker to the same value as the "live" column that was generated. Here is what I mean:

$factory->define(App\File::class, function (Faker $faker) {
    return [
        'identifier' => uniqid(),
        'user_id' => App\User::all()->random()->id,
        'title' => $faker->sentence($nbWords = 4),
        'overview_short' => $faker->sentence,
        'overview' => $faker->text($maxNbChars = 500),
        'price' => $faker->randomFloat($nbMaxDecimals = 2, $min = 0, $max = 125),
        'live' => rand(0, 1),       // So if "live" = 1
        'approved' => rand(0, 1),   // Then I want "approved" = 1
        'finished' => rand(0, 1),   // And "finished" = 1
    ];
})

So if the "live" column gets set to 0, then I want the "approved" and "finished" columns set to 0, or other way around. And the "live" column can be random, 0 or 1

Is there a way to do this in Faker?

// ---------------

Got it,

    $live = rand(0, 1);

    return [
        // .......
        'live' => $live,
        'approved' => $live,
        'finished' => $live
    ];

Solution

  • you should store the random variable be stored into $live, and set 'approved' and 'finished' according to the value