Create Admin Command (Optional)
Create a real admin account without relying on the local-only demo user from Spatie Permissions. Run this after step 04 has installed Spatie Permission and seeded the admin role. The command uses the existing split-name and password validation concerns.
Command
bash
php artisan make:command CreateAdminUserCommand --no-interactionFile: app/Console/Commands/CreateAdminUserCommand.php
php
<?php
namespace App\Console\Commands;
use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules;
use App\Models\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
use Spatie\Permission\Models\Role;
#[Signature('users:create-admin')]
#[Description('Interactively create a verified administrator account')]
class CreateAdminUserCommand extends Command
{
use PasswordValidationRules, ProfileValidationRules;
public function handle(): int
{
if (! Role::query()->where('name', 'admin')->where('guard_name', 'web')->exists()) {
$this->components->error('Admin role is missing. Run php artisan db:seed --class=RoleSeeder first.');
return self::FAILURE;
}
$input = [
'first_name' => $this->ask('First name'),
'last_name' => $this->ask('Last name'),
'email' => $this->ask('Email address'),
'password' => $this->secret('Password'),
'password_confirmation' => $this->secret('Confirm password'),
];
$validator = Validator::make($input, [
...$this->profileRules(),
'password' => $this->passwordRules(),
]);
if ($validator->fails()) {
foreach ($validator->errors()->all() as $message) {
$this->components->error($message);
}
return self::FAILURE;
}
$user = new User([
'first_name' => $input['first_name'],
'last_name' => $input['last_name'],
'email' => $input['email'],
'password' => $input['password'],
]);
$user->email_verified_at = now();
$user->save();
$user->assignRole('admin');
$this->components->info("Administrator {$user->email} created.");
return self::SUCCESS;
}
}The command checks for the admin role before prompting, rejects invalid or duplicate email addresses, and requires password confirmation. It creates an already verified user and assigns the admin role. The model's hashed cast hashes the password; do not hash it a second time.
Verify
In the Laravel application, run php artisan db:seed --class=RoleSeeder if the roles have not been seeded, then:
bash
php artisan users:create-adminEnter the new user's details and a unique email address. Confirm the success message, then check that the account can sign in, has a verified email, and has the admin role. Try a duplicate email or mismatched passwords: validation should fail without creating a user. Keep credentials out of shell history and Git.
Commit
bash
git add -A
git commit -m '10 - Create Admin Command'