Using a Progress Bar while Seeding a database in Laravel
Your code isn't working because you're using $this->output
in the wrong class. If you take a look again to the article you shared, $this-output
is used in an Artisan command class.
In fact, every Artisan command is made with the Symfony Console component.
You're actually trying to use it in a database seeder :)
My suggestion: build your seeders and then call them with an "install" or "seed" customized command for your needs.
Here is my implementation code,
<?php
use Illuminate\Database\Seeder;
class MediaTypeTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$media_types = [
['name'=>'movie'],
['name'=>'channel'],
['name'=>'drama'],
// ['name'=>'ebook'],
// ['name'=>'shopping'],
// ['name'=>'reseller'],
// ['name'=>'broadcasting']
];
$this->command->getOutput()->progressStart(count($media_types));
App\Models\Backoffice\MediaType::query()->delete();
foreach($media_types as $media_type){
App\Models\Backoffice\MediaType::create($media_type);
$this->command->getOutput()->progressAdvance();
}
$this->command->getOutput()->progressFinish();
}
}
You can get access to output through $this->command->getOutput()
public function run()
{
$this->command->getOutput()->progressStart(10);
for ($i = 0; $i < 10; $i++) {
sleep(1);
$this->command->getOutput()->progressAdvance();
}
$this->command->getOutput()->progressFinish();
}