简体   繁体   中英

Laravel 5.3 Model Factories

Simple question about factories:

ModelFactory:

$myarray=[
'cat1',
'cat2', 
'cat3'   
];



 $factory->define(App\Job::class, function (Faker\Generator $faker) {
        return [
            'title' => $faker->randomElement($myarray),
            'firm_id' => $faker->numberBetween($min = 1, $max = 3),
            'user_id' => $faker->numberBetween($min = 1, $max = 5),
        ];
    });

Why it's not working?

And another simple question: Is it possible to pass $myarray in factory from eloquent?

You need to make the closure use your array, to make it available in it :)

$myarray = ['cat1', 'cat2', 'cat3'];

$factory->define(App\Job::class, function (Faker\Generator $faker) use ($myarray) {
    return [
        'title' => $faker->randomElement($myarray),
        'firm_id' => $faker->numberBetween($min = 1, $max = 3),
        'user_id' => $faker->numberBetween($min = 1, $max = 5),
    ];
});

Here is a few examples from the php docs :) http://php.net/manual/en/functions.anonymous.php#example-160

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM