new admin users seeder
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
<?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}."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -17,9 +17,14 @@ class DatabaseSeeder extends Seeder
|
||||
{
|
||||
// User::factory(10)->create();
|
||||
|
||||
User::factory()->create([
|
||||
'name' => 'Test User',
|
||||
'email' => 'test@example.com',
|
||||
//User::factory()->create([
|
||||
// 'name' => 'Test User',
|
||||
// 'email' => 'test@example.com',
|
||||
//]);
|
||||
|
||||
$this->call([
|
||||
AdminUserSeeder::class,
|
||||
]);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user