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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With