Does Laravel pass variables from one seed file to another?

I created several seed files, and my main DatabaseSeeder file looks like this:

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $name1 = "James";
        $name2 = "Jeff";
        $name3 = "Joe";

        $this->call(UserTableSeeder::class);
        $this->call(PersonTableSeeder::class);
        $this->call(IndividualTableSeeder::class);
        $this->call(HumanTableSeeder::class);
    }
}

How can I make UserTableSeeder and PersonTableSeeder get variables from my main seeder file? (What I'm really trying to do is use Faker to output random values, but use the same value for each seeder)

+4
source share
1 answer

I had the same problem, as a result I redefined the call () function by adding $ extra var and passing it to the run () function.

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $name1 = "James";
        $name2 = "Jeff";
        $name3 = "Joe";

        $this->call(UserTableSeeder::class, $name1);
        $this->call(PersonTableSeeder::class);
        $this->call(IndividualTableSeeder::class);
        $this->call(HumanTableSeeder::class);
    }

    public function call($class, $extra = null) {
        $this->resolve($class)->run($extra);

        if (isset($this->command)) {
            $this->command->getOutput()->writeln("<info>Seeded:</info> $class");
        }
    }

}

and then add $ extra to your seed drill class

// database/seeds/UserTableSeeder.php


  /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run($extra = null)
    {
        var_dump($extra);
    }

hope this helps.

+16

All Articles