Add make:admin artisan command for creating admin users
This commit is contained in:
71
src/app/Console/Commands/MakeAdminCommand.php
Normal file
71
src/app/Console/Commands/MakeAdminCommand.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
class MakeAdminCommand extends Command
|
||||
{
|
||||
protected $signature = 'make:admin
|
||||
{email : The email address for the admin user}
|
||||
{--name= : The name for the admin user}
|
||||
{--password= : The password (will prompt if not provided)}';
|
||||
|
||||
protected $description = 'Create a new admin user with full permissions';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$email = $this->argument('email');
|
||||
$name = $this->option('name') ?? $this->ask('Enter admin name', 'Admin');
|
||||
$password = $this->option('password') ?? $this->secret('Enter password');
|
||||
|
||||
// Validate email
|
||||
$validator = Validator::make(
|
||||
['email' => $email],
|
||||
['email' => 'required|email|unique:users,email']
|
||||
);
|
||||
|
||||
if ($validator->fails()) {
|
||||
$this->error('Validation failed:');
|
||||
foreach ($validator->errors()->all() as $error) {
|
||||
$this->error(" - {$error}");
|
||||
}
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// Validate password
|
||||
if (strlen($password) < 8) {
|
||||
$this->error('Password must be at least 8 characters.');
|
||||
return Command::FAILURE;
|
||||
}
|
||||
|
||||
// Create user
|
||||
$user = User::create([
|
||||
'name' => $name,
|
||||
'email' => $email,
|
||||
'password' => Hash::make($password),
|
||||
'email_verified_at' => now(),
|
||||
]);
|
||||
|
||||
// Assign admin role
|
||||
$user->assignRole('admin');
|
||||
|
||||
$this->info("✅ Admin user created successfully!");
|
||||
$this->table(
|
||||
['Field', 'Value'],
|
||||
[
|
||||
['Name', $name],
|
||||
['Email', $email],
|
||||
['Role', 'admin'],
|
||||
]
|
||||
);
|
||||
|
||||
$this->newLine();
|
||||
$this->info("Login at: /admin");
|
||||
|
||||
return Command::SUCCESS;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user