How can I run all seeders within database/seeds folder automatically in laravel?

Viewed 7236

Instead adding all the new seeders files manually one by one into the DatabaseSeeder.php file, Is it possible to automatically run all files within the seeds directory. Is that possible?

PS: Of course (as @DissidentRage mentioned) in this case we should consider that automating such processes can make your seeders independent and can cause a lot trouble too.

3 Answers

Laravel 8 has the following available method (call) you can use inside you DatabaseSeeder.php.

/**
 * Run the database seeders.
 *
 * @return void
 */
public function run()
{
    $this->call([
        UserSeeder::class,
        PostSeeder::class,
        CommentSeeder::class,
    ]);
}

But to reiterate, running seeders like this might not be the best approach.

This is the DatabaseSeeder.php code-snippet I use to automatically execute revisions, it allows you to manipulate the order by adding a numeric version in front of the class-name.

After creating your seeder with php artisan make:seeder you can rename the seed-file

  • From: <orginal-classname>.php
  • To: ####-<orginal-classname>.php
    • The size of your version-number does not matter

It's not required to change the actual class-name of the seeder.

$seedFilePattern = '/([0-9]+)\-([a-z0-9_\-]+)\.php/i';
$files = scandir(dirname(__FILE__)); // Alphabetically sorted
foreach ($files as $key => $file) {
    if (!in_array($file, ['.', '..', 'DatabaseSeeder.php', 'BaseSeeder.php'])) {
        if (preg_match($seedFilePattern, $file, $matches)) {
            [, $version, $class] = $matches;
            $this->call($class);
        } else {
            echo '[WARNING] The file "' . $file . '" does not match the seeding pattern "' . $seedFilePattern . '", rename it accordingly to seed it automagically' . PHP_EOL;
        }
    }
}

My seeds dir for a given project

0001-abcSeeder.php
0002-defSeeder.php
0003-ghiSeeder.php
...
0008-xyzSeeder.php
BaseSeeder.php
DatabaseSeeder.php

If during development need to add something in between you just increase the size of that version ex: 00021

0001-abcSeeder.php
0002-defSeeder.php
00021-ForgotSomethingSeeder.php
0003-ghiSeeder.php
...
0008-xyzSeeder.php
BaseSeeder.php
DatabaseSeeder.php
Related