I need to run a Factory 50
times, so inside the DatabseSeeder
:
public function run()
{
for($i=1;$i<=50;$i++){
(new CategoryQuestionFactory($i))->create();
}
}
So as you can see, I tried passing a variable called $i
as parameter to CategoryQuestionFactory
class.
Then at this Factory, I tried this:
class CategoryQuestionFactory extends Factory
{
protected $counter;
public function __construct($c)
{
$this->counter = $c;
}
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition()
{
$question = Question::find($this->counter);
return [
'category_id' => $this->faker->numberBetween(1,22),
'question_id' => $question->id
];
}
}
But when I run php artisan db:seed
at Terminal, I get this error:
Call to a member function pipe() on null
at
C:xampphtdocsforumrootvendorlaravelframeworksrcIlluminateDatabaseEloquentFactoriesFactory.php:429
So what’s going wrong here? How can I properly send a value as a parameter to the Factory Class?
Also, at the IDE for the __construct
method of this Factory, I get this message:
UPDATE #1:
Here is the capture of error at IDE:
4
Answers
It seems to me that you want to seed the intermediate table. There are methods that can be use when seeding them one of them is
has()
which is the one i always use.So let’s say you want to create a 100 question and 5 categories
In laravel its better to associate with the model, So instead of doing this
you can do this (then you dont have to passs the
$i
)Don’t forget to call
parent::__construct()
in the constructor of yourCategoryQuestionFactory
factory.Your
CategoryQuestionFactory
is supposed to extends Laravel standardFactory
. Missing to call the parent constructor on a child class breaks the code.I’ve generated the model via PhpStrom:
It’s should work fine. I checked. You should call
parent::__construct
.