Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

laravel

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.

like image 460
Skeletor Avatar asked Aug 02 '17 13:08

Skeletor


1 Answers

I run in that question and found this way as an simple answer.

You can easily use scandir() to put all the filenames into an array and then loop through them just using foreach loop. And then call/run them all automatically. This way you don't need to add the new class to the run() method each time you create (mostly with php artisan make:seeder SomeTableSeeder) a seeder.

So instead:

// database/seeds/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{

    public function run() {
        $this->call(UsersTableSeeder::class);
        $this->call(AnotherTableSeeder::class);
        ...
    }

}

Simply use:

// database/seeds/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{

    public function run(){
        $files_arr = scandir( dirname(__FILE__) ); //store filenames into $files_array
        foreach ($files_arr as $key => $file){
            if ($file !== 'DatabaseSeeder.php' && $file[0] !== "." ){
                $this->call( explode('.', $file)[0] );
            }
        }
    }

} 

PS: If you want to exclude a seeder file from this auto run process, just add a single dot to the beginning of the filename.

PS2: If you want to change the excluder character dot for any reason. Just prepend your desired excluder character to the if expressions (like for underscore character prepend && $file[0] !== "_"). Don't change the $file[0] !== "." expression because it extends the scandir() methods . and .. folders as well.

like image 68
Skeletor Avatar answered Jan 04 '23 11:01

Skeletor