How to declare $faker in the seed file in Laravel when overriding for argument to factory?

Lisendra picture Lisendra · Jul 3, 2020 · Viewed 7.2k times · Source

I am trying to create multiple model of seeds like seedt1, seedt2, seedt3 with parameters for the sample.

I am aware of factory states, i don't want to use it,i want to keep my factory model minimal and clean as possible.

i have my model factory:

and my seed file:

<?php

use Illuminate\Database\Seeder;

class sampleT1 extends Seeder
{

    public function run()
    {

        factory('App\User', 1)->create(['role_id' =>'2',]); //1 financial user id 2
        factory('App\User', 3)->create(['role_id' =>'4',]); //3 managers id 3-5
        factory('App\User', 5)->create(); //10 users id 6-10
        factory('App\Client', 300)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10),]); //300 clients
        factory('App\Query', 1000)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10), 'client_id' => $faker->numberBetween($min = 1, $max = 300),]); //300 queries
        factory('App\Task', 5000)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10), 'query_id' => $faker->numberBetween($min = 1, $max = 250),]); //5000 tasks
        //factory('App\User', 50)->states('premium', 'delinquent')->create();

    }
}

when i run my seed with : php artisan db:seed --class=sampleT1

i get result:

deployer@debdaddytp:/var/www/mice$ php artisan db:seed --class=sampleT1

   ErrorException 

  Undefined variable: faker

  at database/seeds/sampleT1.php:20

obviously the variable of faker is not inherited from the model factory, how should i declare it in my seed for this to work?

Answer

tillsanders picture tillsanders · Jan 23, 2021

It's always a good idea to keep things consistent, so I would suggest doing it the same way as the Factory class does it. Your seeder would then look like this:

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Faker\Generator;
use Illuminate\Container\Container;

class MySeeder extends Seeder
{
    /**
     * The current Faker instance.
     *
     * @var \Faker\Generator
     */
    protected $faker;

    /**
     * Create a new seeder instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->faker = $this->withFaker();
    }

    /**
     * Get a new Faker instance.
     *
     * @return \Faker\Generator
     */
    protected function withFaker()
    {
        return Container::getInstance()->make(Generator::class);
    }

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // ...
    }
}