Send value as parameter to factory class
P粉378890106
P粉378890106 2024-01-03 14:42:16
0
1
497

I need to run the factory 50 times, so within DatabseSeeder:

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

As you can see, I tried passing a variable named $i as a parameter to the CategoryQuestionFactory class.

Then in 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 in the terminal, I get this error:

Call member function pipeline() on null

exist C:xampphtdocsforumrootvendorlaravelframeworksrcIlluminateDatabaseEloquentFactoriesFactory.php:429

So what’s the problem here? How to correctly send values ​​as parameters to factory classes?

Additionally, in the IDE for the factory's __construct method, I get the following message:


Update #1:

The following is the error capture in the IDE:

P粉378890106
P粉378890106

reply all(1)
P粉447785031

It seems to me that you want to seed the intermediate table. There are a few methods you can use when seeding, one of them is has(), which is the method I often use.

/**
* will create a one question and 3 category then create a data in the intermediate table. 
* expected data : 
* question_id | category_id
*     1            1
*     1            2
*     1            3
*/
Question::factory()->has(
    Category::factory()->count(3)
)->create();

Suppose you want to create 100 questions and 5 categories

/**
* will create a 100 question and 5 category then create a data in the intermediate table. 
* expected data : 
* question_id | category_id
*     1            1
*     1            2
*     1            3
*     1            4
*     1            5
*     2            1
*     2            2
*     2            3
*     2            4
*     2            5
* until the 100th question will have a 5 categories
*/
Question::factory(100)->has(
    Category::factory()->count(5)
)->create();
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template