Last active
March 5, 2024 02:20
-
-
Save meigwilym/d8ac0b724b4ef9c20ed7768c92838d92 to your computer and use it in GitHub Desktop.
Laravel Create User Command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// routes/console.php | |
// quickly create an user via the command line | |
Artisan::command('user:create', function () { | |
$name = $this->ask('Name?'); | |
$email = $this->ask('Email?'); | |
$pwd = $this->ask('Password?'); | |
// $pwd = $this->secret('Password?'); // or use secret() to hide the password being inputted | |
\DB::table('users')->insert([ | |
'name' => $name, | |
'email' => $email, | |
'password' => bcrypt($pwd), | |
'created_at' => date_create()->format('Y-m-d H:i:s'), | |
'updated_at' => date_create()->format('Y-m-d H:i:s'), | |
]); | |
$this->info('Account created for '.$name); | |
}); |
Suggested updates to make it a little cleaner and streamlined
// quickly create an user via the command line
Artisan::command('user:create', function () {
\App\User::create([
'name' => $this->ask('Name?'),
'email' => $this->ask('Email?'),
'password' => bcrypt($this->secret('Password?')),
]);
$this->info('Account created ');
});
... Wee bit more robust.
<?php
namespace App\Console\Commands;
use App\Models\User;
use Bouncer;
use Illuminate\Console\Command;
use Silber\Bouncer\Database\Role;
class UserMakeCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user:make';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new user';
protected $rolesMap = [];
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
//$this->rolesMap = Role::all()->pluck('title', 'id')->toArray();
do {
$details = $this->askForUserDetails($details ?? null);
$name = $details['name'];
$email = $details['email'];
$password = $details['password'];
//$role = $details['role'];
} while (!$this->confirm("Create user {$name} <{$email}>?", true));
$user = User::forceCreate(['name' => $name, 'email' => $email, 'password' => \Hash::make($password)]);
//$user->roles()->attach(array_flip($this->rolesMap)[$role]);
$this->info("Created new user #{$user->id}");
}
/**
* @param null $defaults
* @return array
*/
protected function askForUserDetails($defaults = null)
{
$name = $this->ask('Full name of user?', $defaults['name'] ?? null);
$email = $this->askUniqueEmail('Email Address for user?', $defaults['email'] ?? null);
$password = $this->ask('Password for user? (will be visible)', $defaults['password'] ?? null);
$role = null;//$this->choice('Which role should this user have?', $this->rolesMap, $defaults['role'] ?? null);
return compact('name', 'email', 'password', 'role');
}
/**
* @param $message
* @param null $default
* @return string
*/
protected function askUniqueEmail($message, $default = null)
{
do {
$email = $this->ask($message, $default);
} while (!$this->checkEmailIsValid($email) || !$this->checkEmailIsUnique($email));
return $email;
}
/**
* @param $email
* @return bool
*/
protected function checkEmailIsValid($email)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error('Sorry, "' . $email . '" is not a valid email address!');
return false;
}
return true;
}
/**
* @param $email
* @return bool
*/
public function checkEmailIsUnique($email)
{
if ($existingUser = User::whereEmail($email)->first()) {
$this->error('Sorry, "' . $existingUser->email . '" is already in use by ' . $existingUser->name . '!');
return false;
}
return true;
}
}
With some minor changes.
Artisan::command('user:create', function () {
$name = $this->ask('Name?');
$email = $this->ask('Email?');
$pwd = $this->secret('Password?');
User::query()
->create([
'name' => $name,
'email' => $email,
'password' => Hash::make($pwd),
]);
$this->info('Account created for '.$name);
});
Updated to use laravel/prompts
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\info;
use function Laravel\Prompts\password;
use function Laravel\Prompts\select;
use function Laravel\Prompts\text;
class CreateUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'make:user';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new user';
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
//$this->rolesMap = Role::all()->pluck('title', 'id')->toArray();
$details = $this->askForUserDetails($details ?? null);
$name = $details['name'];
$email = $details['email'];
$password = $details['password'];
$role = $details['role'] == 'helper' ? false : true;
confirm("Create user {$name} <{$email}> as {$details['role']}?", true);
$user = User::forceCreate(['name' => $name, 'email' => $email, 'password' => Hash::make($password), 'is_admin' => $role]);
//$user->roles()->attach(array_flip($this->rolesMap)[$role]);
info("Created new user {$user->email}");
}
/**
* @param null $defaults
* @return array
*/
protected function askForUserDetails($defaults = null)
{
$name = text(
label: 'What is the users name?',
placeholder: 'E.g. Brian Retterer',
);
$email = text(
label: 'What is the users email address?',
placeholder: 'E.g. [email protected]',
validate: fn (string $value) => match (true) {
!filter_var($value, FILTER_VALIDATE_EMAIL) => 'The email is invalid.',
(User::query()->where('email', $value)->first() != null) => 'The email already exists.',
default => null
}
);
$password = password(
label: 'What is the users password?',
placeholder: 'password',
hint: 'Minimum 8 characters.',
required: true,
validate: fn (string $value) => match (true) {
strlen($value) < 8 => 'The password must be at least 8 characters.',
default => null
}
);
$role = select(
label: 'What role should the user have?',
options: [
'helper' => 'Helper',
'admin' => 'Admin',
],
default: 'helper'
);
return compact('name', 'email', 'password', 'role');
}
}```
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great snippet. Why not make Password a
secret
? 😄