Home  >  Q&A  >  body text

Send value as parameter to factory class

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粉378890106P粉378890106313 days ago475

reply all(1)I'll reply

  • P粉447785031

    P粉4477850312024-01-04 13:12:02

    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();

    reply
    0
  • Cancelreply