Skip to content

Instantly share code, notes, and snippets.

@anovsiradj
Last active May 30, 2023 12:36
Show Gist options
  • Save anovsiradj/b3eb18af34571d9b2beed0fbeadea43c to your computer and use it in GitHub Desktop.
Save anovsiradj/b3eb18af34571d9b2beed0fbeadea43c to your computer and use it in GitHub Desktop.
Laravel command untuk melakukan seeder untuk semua model (secara manual)
<?php
namespace App\Console\Commands;
use App\Models\Kabupaten;
use App\Models\Provinsi;
use App\Models\User;
use Faker\Factory;
use Faker\Generator;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
class ModelFeeder extends Command
{
private $models = [
User::class,
Provinsi::class,
Kabupaten::class,
];
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:model-feeder';
/**
* The console command description.
*
* @var string
*/
protected $description;
/**
* Execute the console command.
*/
public function handle()
{
dump($this->models);
$class = $this->ask('model', 0);
$class = $this->models[$class];
$modelCount = $class::count();
$customCount = $this->ask('length', 10);
$faker = Factory::create('id_ID');
for ($i = 0; $i < ($customCount - $modelCount); $i++) {
$model = new $class;
$this->feed($faker, $model);
$model->save();
}
}
private function feed(Generator $faker, $model)
{
static $cache = [];
if ($model instanceof User) {
$model->fillable(['name', 'email', 'password']);
$model->fill([
'name' => $faker->name,
'email' => $faker->email,
'password' => Hash::make('password'),
]);
}
if ($model instanceof Provinsi) {
$model->fillable(['nama_provinsi']);
$model->fill([
'nama_provinsi' => $faker->city,
]);
}
if ($model instanceof Kabupaten) {
$cache['id_provinsi'] ??= Provinsi::query()->pluck('id');
$model->fillable(['id_provinsi', 'nama_kabupaten', 'jumlah_penduduk']);
$model->fill([
'id_provinsi' => $faker->randomElement($cache['id_provinsi']),
'nama_kabupaten' => $faker->city,
'jumlah_penduduk' => $faker->numberBetween(111, 999),
]);
}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment