How to increment variable defined at a Factory

172 views Asked by At

I'm using Laravel 9 and I have made this Factory which inserts some data into a pivot table between Question && Category Models:

class CategoryQuestionFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        if(isset($counter)){
            $question = Question::find($counter);
        }else{
            $counter = 1;
            $question = Question::find($counter);
        }

        return [
            'category_id' => $this->faker->numberBetween(1,22),
            'question_id' => $question->id
        ];

        $counter++;
    }
}

Basically, the first time when this Factory runs, it will insert question_id of 1 and a random number between 1 & 22 as category_id.

But because I need to run this Factory more than one time (it should runs 50 times), I added this code to DatabaseSeeder.php:

public function run()
{
    for($i=0;$i<50;$i++){
        (new CategoryQuestionFactory())->create();
    }
}

But because for the next times, I don't want to insert question_id of 1 again, I have defined a variable called $counter which increments at the end of function as well (to get the next record of question at questions table):

        if(isset($counter)){
            $question = Question::find($counter);
        }else{
            $counter = 1;
            $question = Question::find($counter);
        }

        return [
            ...
        ]

        $counter++;

But now the problem is, the value of $counter does not gets incremented and therefor, it inserts 1 for the all fifty times.

So the question is, how can I define a variable at Factory function, so the next time it runs the code, this variable is already incremented and no need to start from scratch.


UPDATE #1:

enter image description here


UPDATE #2:

enter image description here

1

There are 1 answers

5
dz0nika On

Laravel 8 introduced new factory classes so your request can look like:

class CategoryQuestionFactory extends Factory {

    private static $questionId = 1;

    protected $model = Question::class;

    public function definition() {
         $question = Question::find(self::$questionId);

         self::$questionId++;
         return [
            'category_id' => $this->faker->numberBetween(1,22),
            'question_id' => $question->id
        ];

    }

And in you database seeder add the following

CategoryQuestion::factory()->times(50)->create();