Provided that Machine
class is a model, you can extract the state out and build the returned array
Set $state
to random 0
or 1
and use a ternary operator to generate a random element for a comment
based on whether the state
is true or false
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Machine;
use Faker\Generator as Faker;
$factory->define(Machine::class, function (Faker $faker) {
$state = $faker->randomElement([0, 1]);
return [
'name' => $faker->name,
'state' => $state,
'comment' => $state ? $faker->randomElement(['Malogrado', 'Estropeado']) : null,
];
});
Given a migration that looks like this
Schema::create('machines', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->boolean('state');
$table->string('comment')->nullable();
$table->timestamps();
});
And seed that data
public function run()
{
factory('App\Machine', 5)->create(); // Create 5 random machines
}
Result
>>> App\Machine::all();
=> Illuminate\Database\Eloquent\Collection {#3011
all: [
App\Machine {#3012
id: 1,
name: "Twila Heaney",
state: 0,
comment: null,
created_at: "2019-11-16 16:15:01",
updated_at: "2019-11-16 16:15:01",
},
App\Machine {#3013
id: 2,
name: "Dr. Floy Hilpert Sr.",
state: 1,
comment: "Malogrado",
created_at: "2019-11-16 16:15:01",
updated_at: "2019-11-16 16:15:01",
},
App\Machine {#3014
id: 3,
name: "Kailey Reilly",
state: 0,
comment: null,
created_at: "2019-11-16 16:15:01",
updated_at: "2019-11-16 16:15:01",
},
App\Machine {#3015
id: 4,
name: "Hilbert Lemke",
state: 0,
comment: null,
created_at: "2019-11-16 16:15:01",
updated_at: "2019-11-16 16:15:01",
},
App\Machine {#3016
id: 5,
name: "Kathleen Hessel PhD",
state: 1,
comment: "Estropeado",
created_at: "2019-11-16 16:15:01",
updated_at: "2019-11-16 16:15:01",
},
],
}
Hope this helps
Machine
class? is it a model?