Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random select value on array factory Laravel

Tags:

laravel-5

I had user migration:

$table->enum('type',['seller','buyer'])->default('seller');

I want when using ModelFactory how to get random value seller or buyer?

$factory->define(App\User::class, function (Faker\Generator $faker) {

    static $password;

    return [
        'firstName' => $faker->name,
        'lastName' => $faker->name,
        'username' => $faker->unique()->username,
        'email' => $faker->unique()->safeEmail,
        'password' => md5('user123'),
        'bio' => $faker->sentence(3, true),
        'type' => ???,
    ];
});
like image 777
Nguyen Manh Linh Avatar asked Jun 04 '17 04:06

Nguyen Manh Linh


2 Answers

Make use of randomElement method

'type' => $faker->randomElement(['seller', 'buyer']), 
like image 117
Sandeesh Avatar answered Sep 17 '22 18:09

Sandeesh


Laravel version >= 5.6

use Illuminate\Support\Arr;  $array = [1, 2, 3, 4, 5];  $random = Arr::random($array);  // 4 - (retrieved randomly)  "type" => Arr::random($array); 
like image 39
UserHelpNeeding02356 Avatar answered Sep 17 '22 18:09

UserHelpNeeding02356