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.


Laravel 8 introduced new factory classes so your request can look like:
And in you database seeder add the following