87 lines
2.1 KiB
PHP
87 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace Database\Seeders;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Database\Seeder;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use RuntimeException;
|
|
use Spatie\Permission\Models\Role;
|
|
|
|
class AdminUserSeeder extends Seeder
|
|
{
|
|
public function run(): void
|
|
{
|
|
if (! $this->command) {
|
|
throw new RuntimeException(
|
|
'AdminUserSeeder must be run interactively through Artisan.'
|
|
);
|
|
}
|
|
|
|
$name = trim((string) $this->command->ask(
|
|
'Administrator name',
|
|
'Administrator'
|
|
));
|
|
|
|
$email = strtolower(trim((string) $this->command->ask(
|
|
'Administrator email',
|
|
'admin@example.com'
|
|
)));
|
|
|
|
if (User::query()->where('email', $email)->exists()) {
|
|
$this->command->warn(
|
|
"A user with the email {$email} already exists. No changes were made."
|
|
);
|
|
|
|
return;
|
|
}
|
|
|
|
do {
|
|
$password = $this->command->secret(
|
|
'Administrator password'
|
|
);
|
|
|
|
$confirmation = $this->command->secret(
|
|
'Confirm administrator password'
|
|
);
|
|
|
|
if (! is_string($password) || strlen($password) < 12) {
|
|
$this->command->error(
|
|
'The password must contain at least 12 characters.'
|
|
);
|
|
|
|
continue;
|
|
}
|
|
|
|
if ($password !== $confirmation) {
|
|
$this->command->error(
|
|
'The passwords do not match.'
|
|
);
|
|
|
|
continue;
|
|
}
|
|
|
|
break;
|
|
} while (true);
|
|
|
|
$role = Role::firstOrCreate([
|
|
'name' => 'admin',
|
|
'guard_name' => 'web',
|
|
]);
|
|
|
|
$user = User::query()->create([
|
|
'name' => $name,
|
|
'email' => $email,
|
|
'password' => Hash::make($password),
|
|
'email_verified_at' => now(),
|
|
]);
|
|
|
|
$user->assignRole($role);
|
|
|
|
$this->command->newLine();
|
|
$this->command->info(
|
|
"Administrator account created for {$user->email}."
|
|
);
|
|
}
|
|
}
|