Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincej's avatar
Level 15

Is there a utility some where which parses my migrations and creates a seed file ?

If there is not, then this would be a great idea for someone with the skills and time to build it.

Essentially I find myself typing out all the fields of a DB migration. Then that done, I have to type them all out again for a DB seed file.

Would it not be great to be able to parse the migration file and generate a template for a seed file / stub, so that all the user has to do is add the appropriate value ?

So the generated seed stub might look like:

class ProductTableSeeder extends Seeder {

    public function run()
    {
        Eloquent::unguard();

        $faker=Faker\Factory::create();

        foreach(range(1,15)as $index)
        {
            Product::create([
                'name'=>$faker->
               'product_code'=>$faker->
                'description'=>$faker->
                'long_descritpion'=>$faker->
etc etc
                ]);

        }
    }
} 

Just a thought ....

0 likes
62 replies
bashy's avatar

Good idea and I haven't seen one around but I normally use Jeffrey's generators to create stubs. That in turn just creates this though

<?php

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class ModelTableSeeder extends Seeder {

 public function run()
 {
  $faker = Faker::create();

  foreach(range(1, 10) as $index)
  {
   Model::create([

   ]);
  }
 }

}
vincej's avatar
Level 15

sure - that goes part of the way there. Some of my DB tables have 20 fields. Gets to be a real waste of time having to type them all in twice.

HRcc's avatar

If you're using Sublime Text or PhpStorm (or something similar), you can easily use multi-cursor selects to help you with that ;)

1 like
vincej's avatar
Level 15

I use Storm.Yeah I guess it would help. You would need to first copy and paste your migration values, then with your multi cursor delete all the stuff you son't want then add the $faker->

You don't even need to parse the migration file, just parse the DB table for the field names. Then concatenate the $faker-> inside a stub similar to Jeffrey's.

bestmomo's avatar

I made this command on L5, I think it works too on L4 with minimal changes.

First the app/Console/Commands/stubs/seed.stub :

<?php

use Illuminate\Database\Seeder;

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class {{class}} extends Seeder {

    public function run()
    {
        $faker = Faker::create();

        foreach(range(1, 10) as $index)
        {
            Model::create([
                {{fields}}
            ]);
        }
    }

}

And the app/Console/Commands/SeedCommand.php :

<?php namespace App\Console\Commands;

use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputOption;
use Schema;

class SeedCommand extends GeneratorCommand {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:seed';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new Seeder class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Seeder';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.'/stubs/seed.stub';
    }

    /**
     * Render the fields
     *
     * @param  array  $columns
     * @param  string $stub
     * @return void
     */
    protected function render($columns, &amp;$stub)
    {
        $fields = '';
        foreach ($columns as $index => $column) {
            $fields .= ($index != 0 ? "\t\t\t\t" : '') . "'$column' => " . '$faker->' . ($index != count($columns) - 1 ? ",\r\n" : '');
        }
        $stub = str_replace('{{fields}}', $fields, $stub);
    }

    /**
     * Build the seed with the given name.
     *
     * @param  string  $name
     * @return string
     */
    protected function buildClass($name)
    {
        $stub = $this->files->get($this->getStub());

        return $this->replaceNamespace($stub, $name)->replaceFields($stub)->replaceClass($stub, $name);
    }

    /**
     * Get the destination path.
     *
     * @param  string  $name
     * @return string
     */
    protected function getPath($name)
    {
        $name = str_replace($this->getAppNamespace(), '', $name);

        return $this->laravel['path.database'].'/seeds/' . $name . '.php';
    }

    /**
     * Fill the fields for the given stub.
     *
     * @param  string  $stub
     * @return $this
     */
    protected function replaceFields(&amp;$stub)
    {
        // Get the table name
        $table = $this->option('table');

        // Test if table exists
        if (Schema::hasTable($table))
        {
            // Get the table columns
            $columns = Schema::getColumnListing($table);
            // Render
            $this->render($columns, $stub);
        }

        return $this;
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['table', null, InputOption::VALUE_REQUIRED, 'The table name.', null]
        ];
    }

}

Syntax is :

php artisan make:seed MySeeder --table=mytable

Seeder must be created in seeds directory...

1 like
vincej's avatar
Level 15

I am sorry to appear to be such a newb to Laravel - where do I install this ?

bashy's avatar

It's an artisan command so you can put (and modify for L4) in the commands folder

bestmomo's avatar

I gave the paths above to install files. And to make it working for L5 you must inform app/Console/Kernel.php :

    protected $commands = [
       ...
        'App\Console\Commands\SeedCommand',
    ];

I looked for L4, there are many changes and it's not so easy, so I made it :

<?php 

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class SeedCommand extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:seed';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new Seeder class';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'Seeder';

    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        return __DIR__.'/stubs/seed.stub';
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $name = $this->argument('name');

        if (File::exists($path = $this->getPath($name)))
        {
            return $this->error($this->type.' already exists!');
        }

        $this->buildClass($name);

        $this->info($this->type.' created successfully.');
    }

    /**
     * Write the seed file to disk.
     *
     * @param  string  $name
     * @param  string  $stub
     * @return string
     */
    protected function writeSeed($name, $stub)
    {
        $path = $this->getPath($name);

        File::put($path, $stub);
    }

    /**
     * Render the fields
     *
     * @param  array  $columns
     * @param  string $stub
     * @return void
     */
    protected function render($columns, &amp;$stub)
    {
        $fields = '';
        foreach ($columns as $index => $column) {
            $fields .= ($index != 0 ? "\t\t\t\t" : '') . "'$column' => " . '$faker->' . ($index != count($columns) - 1 ? ",\r\n" : '');
        }
        $stub = str_replace('{{fields}}', $fields, $stub);
    }

    /**
     * Build the seed with the given name.
     *
     * @param  string  $name
     * @return string
     */
    protected function buildClass($name)
    {
        $stub = File::get($this->getStub());

        $this->replaceFields($stub)->replaceClass($stub, $name)->writeSeed($name, $stub);
    }

    /**
     * Get the destination path.
     *
     * @param  string  $name
     * @return string
     */
    protected function getPath($name)
    {
        return $this->laravel['path'].'/database/seeds/' . $name . '.php';
    }

    /**
     * Fill the fields for the given stub.
     *
     * @param  string  $stub
     * @return $this
     */
    protected function replaceFields(&amp;$stub)
    {
        // Get the table name
        $table = $this->option('table');

        // Test if table exists
        if (Schema::hasTable($table))
        {
            // Get the table columns
            $columns = Schema::getColumnListing($table);
            // Render
            $this->render($columns, $stub);
        }

        return $this;
    }

    /**
     * Fill the class for the given stub.
     *
     * @param  string  $stub
     * @return $this
     */
    protected function replaceClass(&amp;$stub, $name)
    {
        $stub = str_replace('{{class}}', $name, $stub);

        return $this;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['name', InputArgument::REQUIRED, 'Name of the seeder class'],
         ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['table', null, InputOption::VALUE_REQUIRED, 'The table name.', null]
        ];
    }

}

For L4 and that in app/start/artisan.php :

Artisan::add(new SeedCommand);
vincej's avatar
Level 15

HI - Thank you very much for putting the time and effort into this !

I'm using L4.2. I must be doing something wrong at the most very basic level. I paste the code into a file I have created under app/command and called it "SeedCommand". Storm gives me a sea of errors.

Ok, so I try pasting it into start/artisan - and again a sea of errors.

What am I doing wrong ?

Many Thanks !

bestmomo's avatar

For L4 the good place is app/commands/SeedCommand.php. Take the good version (the first one is for L5). And declare it in app/start/artisan.php as I show above.

Put the stub in app/commands/stubs/seed.stub.

vincej's avatar
Level 15

I'm very very sorry, but I do not understand your instructions very well. I am sure it is my fault.

1) I have placed the L4 version inside app/commands/SeedCommand (I am getting errors)

2) I have placed "Artisan::add(new SeedCommand);" inside of start/artisan.

3) "Put the stub in app/commands/stubs/seed.stub." I do not understand what code refers to.

bashy's avatar

For number 3, check a few replies up, he posts the stub for the template of the seed file.

vincej's avatar
Level 15

sorry bashy, I don't know what a stub for the template even looks like or what to do with it.

is this it:

Artisan::add(new SeedCommand);

or maybe:

    protected $commands = [
       ...
        'App\Console\Commands\SeedCommand',
    ];

where do I put it ?

bashy's avatar

It's the stub part a few replies up

First the app/Console/Commands/stubs/seed.stub :

<?php

use Illuminate\Database\Seeder;

// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;

class {{class}} extends Seeder {

    public function run()
    {
        $faker = Faker::create();

        foreach(range(1, 10) as $index)
        {
            Model::create([
                {{fields}}
            ]);
        }
    }

}
vincej's avatar
Level 15

@bashy, Many Thanks for your direction - I have not yet reviewed Jeffey's lessons on CLI apps.

Ok - I believe I have done exactly what has been prescribed. However, I'm not getting much of a result yet.

1) In L4 there is no console directory so I created one and moved the commands directory into it as instructed.

2) I placed the L4 code into SeedCommand.php - it is giving a mountain of errors.

3) I have placed

artisan::add(new SeedCommand);

into start/artisan

4) I created a folder stubs inside app/console/commands and placed the stub code inside it with a file extension as .stub. I also gave the file itself php tags.

bestmomo's avatar

Dont create a Console directory on L4. You must put all in app/commands :

  • app/commands/SeedCommand.php
  • app/commands/stubs/seed.stub
vincej's avatar
Level 15

Many thanks. Ok - great, I removed console and placed everything into the 2 directories as described above.

I am still getting a sea of errors on the SeedCommand.php file.

For clarity, I am using the version on page 1 which is given immediately below your words:

"I looked for L4, there are many changes and it's not so easy, so I made it :"

bashy's avatar

Yeah that was for L5, thought you knew where it was in L4, sorry!

bestmomo's avatar

Oh I see ! &$stub is becomming &amp;$stub in code ! Change all instances.

vincej's avatar
Level 15

Horray - no more errors !

Ok - so I tried to create a seed table with:

 php artisan make:seed MySeeder --table=crews

and I got an error:

 [InvalidArgumentException]                              
  There are no commands defined in the "make" namespace. 
bestmomo's avatar

Is the command present in the list of artisan commands ?

vincej's avatar
Level 15

Yes. start/artisan has only 1 command: Artisan::add(new SeedCommand);

This is on line 14

Yet, when I attempt to run a command I am now also getting:

PHP Fatal error: Class 'SeedCommand' not found in /var/www/auburntree/app/start/artisan.php on line 14
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'SeedCommand' not found","file":"\/var\/www\/auburntree\/app\/start\/artisan.php","line":14}}vince@vince-XPS-8300 /var/www/auburntree $ 
bestmomo's avatar

hum.. it doesn't get the class, try a dumpautoload...

vincej's avatar
Level 15

If I just type this command in the terminal I get:

vince@vince-XPS-8300 /var/www/auburntree $ php artisan
PHP Fatal error: Class 'SeedCommand' not found in /var/www/auburntree/app/start/artisan.php on line 14
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'SeedCommand' not found","file":"\/var\/www\/auburntree\/app\/start\/artisan.php","line":14}}vince@vince-XPS-8300 /var/www/auburntree $ 
vincej's avatar
Level 15

If I use a standard artisan db:seed L4 command it now also fails with the same error message:

vince@vince-XPS-8300 /var/www/auburntree $ php artisan db:seed --class=ContractorsTableSeeder
PHP Fatal error: Class 'SeedCommand' not found in /var/www/auburntree/app/start/artisan.php on line 14
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Class 'SeedCommand' not found","file":"\/var\/www\/auburntree\/app\/start\/artisan.php","line":14}}vince@vince-XPS-8300 /var/www/auburntree $ 
Next

Please or to participate in this conversation.