Initial commit
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Student;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class GenerateStudentSelfServiceCodes extends Command
|
||||
{
|
||||
protected $signature = 'students:generate-self-service-codes {--reset : Generate ulang walau kode sudah ada}';
|
||||
protected $description = 'Generate kode akses self-service untuk siswa';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$students = Student::query()
|
||||
->whereNull('deleted_at')
|
||||
->when(! $this->option('reset'), fn ($query) => $query->whereNull('self_service_access_code'))
|
||||
->get();
|
||||
|
||||
if ($students->isEmpty()) {
|
||||
$this->info('Tidak ada siswa yang perlu dibuatkan kode akses.');
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$bar = $this->output->createProgressBar($students->count());
|
||||
$bar->start();
|
||||
|
||||
foreach ($students as $student) {
|
||||
$student->forceFill([
|
||||
'self_service_access_code' => $this->generateUniqueCode(),
|
||||
'self_service_code_generated_at' => now(),
|
||||
])->save();
|
||||
|
||||
$bar->advance();
|
||||
}
|
||||
|
||||
$bar->finish();
|
||||
$this->newLine(2);
|
||||
$this->info('Kode akses self-service berhasil digenerate.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
protected function generateUniqueCode(): string
|
||||
{
|
||||
do {
|
||||
$code = strtoupper(Str::random(8));
|
||||
} while (Student::where('self_service_access_code', $code)->exists());
|
||||
|
||||
return $code;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user