forrestedw
forrestedw

Reputation: 395

How do you pass variables to a Factory in Laravel?

How do/can I selectively pass numbers to a Laravel Factory, so that if I don't provide the numbers it does its default thing, and if I do it uses them?

For example I have a Student model. It generates a random male or female student with a 50% chance of having a middle name using Faker as expected. It looks like this:

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

    $gender = $faker->randomElement($array = array ('m','f'));
    $has_middle_name = $faker->boolean($chanceOfGettingTrue = 50);
    $student = [];

    if ($gender == 'm') {
        $student['first_name'] = $faker->firstNameMale;
        if ($has_middle_name) {
            $student['middle_name'] = $faker->middleNameMale;
        }
    } else {
        $student['first_name'] = $faker->firstNameFemale;
        if ($has_middle_name) {
            $student['middle_name'] = $faker->firstNameMale;
        }       
    }

    $student['last_name'] = $faker->lastName;
    $student['gender'] = $gender;

    $student['birth_date'] = $faker->dateTimeBetween($startDate = '-18 years', $endDate = '-4 years', $timezone = null);

    return $student;

});

I have seen that I can use State as a way to pass vars. For example I can do something like this:

$student = factory(App\Student::class)->state('male')->make();

Which will call this bit of my factory and so modifies the first_name, middle_name and gender attributes to be consistent with male:

$factory->state(App\Student::class, 'male', function (Faker $faker) {

    $student = [];
    $student['first_name'] = $faker->firstNameMale;
    $has_middle_name = $faker->boolean($chanceOfGettingTrue = 50);
    if ($has_middle_name) {
        $student['middle_name'] = $faker->middleNameMale;
    }    
    $student['gender'] = 'm';

    return $student;

});

However, my code above creates a student in the age range of 4 to 18. What if I want to create a student of a particular age? I know that I could do this to make a student between 8 and 9:

$birth_date = $faker->dateTimeBetween($startDate = '-9 years', $endDate = '-9 years', $timezone = null);
$student = faker(App\Student::class)->make(['birth_date' => $birth_date]);

But I'd rather do something like this:

$student = faker(App\Student::class)->make($minAge = 8, $maxAge = 9);

Is this possible??

Upvotes: 1

Views: 2603

Answers (1)

Vishal Ribdiya
Vishal Ribdiya

Reputation: 880

You can define min_age and max_age into your Student model factory and use below code :

$student = faker(App\Student::class)->make(['min_age' => 8, 'max_age' => 9]);

Upvotes: 1

Related Questions