Skip to content

Instantly share code, notes, and snippets.

@ajaxray
Last active June 11, 2023 15:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ajaxray/d137a330716992cb27c33699f6cd7bec to your computer and use it in GitHub Desktop.
Save ajaxray/d137a330716992cb27c33699f6cd7bec to your computer and use it in GitHub Desktop.
A Laravel Artisan command for creating user with name, email and password

CreateUser

Laravel Artisan command for creating user with name, email and password

How to use?

Just put the CreateUser.php at app/Console/Commands/CreateUser.php. Then you'll get a command app:create-user to run with artisan.

Example

Run the following command from Laravel project directory.

php artisan app:create-user {username} {user@domain.com} {mypassword}

The password will be autimatically encrypted and the user will be created.

Simple, isn't it? 😎

Notes

  1. There is a --unverified option. If you use it, the created user will remain unverified. Otherwise the user be created a email verified by default.
  2. You should put the CreateUserTest.php at tests/Feature/Console/CreateUserTest.php.
  3. The command with not allow duplicate Username and email address (see validations).

Testdox

Create User (Tests\Feature\Console\CreateUser)
 ✔ User creates with valid args
 ✔ Cannot create user with invalid email
 ✔ Cannot create user with duplicate name
 ✔ Cannot create user with duplicate email
 ✔ Created users are verified by default
 ✔ Created users can be kept unverified

OK (6 tests, 19 assertions)
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Validator;
class CreateUser extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:create-user
{name : The username of the user}
{email : The email of the user}
{password : Password in plain text (will be encrypted automatically)}
{--unverified : Keep the user unverified. Otherwise, email verified will be set at current time.}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a user to access the admin panel';
private array $rules = [
'name' => ['required', 'min:4', 'unique:users,name'],
'email' => ['required', 'email', 'unique:users,email'],
'password' => ['required', 'min:6'],
];
/**
* Execute the console command.
*/
public function handle(): int
{
$validator = Validator::make([
'name' => $this->argument('name'),
'email' => $this->argument('email'),
'password' => $this->argument('password'),
], $this->rules);
try {
$userData = $validator->validated();
$userData['password'] = bcrypt($userData['password']);
$userData['email_verified_at'] = $this->option('unverified') ? NULL : now();
User::factory()->create($userData);
$this->info('User created.');
} catch (\Exception $e) {
$this->error("ERROR: {$e->getMessage()} [Code: {$e->getCode()}]");
return 1;
}
return 0;
}
}
<?php
namespace Tests\Feature\Console;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Carbon;
use Tests\TestCase;
class CreateUserTest extends TestCase
{
use RefreshDatabase;
public function test_user_creates_with_valid_args(): void
{
$this->artisan('app:create-user', [
'name' => 'ajaxray',
'email' => 'user@ajaxray.com',
'password' => '12345678',
])->expectsOutputToContain('User created');
$this->assertDatabaseCount('users', 1);
}
public function test_cannot_create_user_with_invalid_email(): void
{
$this->artisan('app:create-user', [
'name' => 'ajaxray',
'email' => 'user@.com',
'password' => '222222',
])->assertFailed()
->expectsOutputToContain('must be a valid email address.');
$this->assertDatabaseEmpty('users');
}
public function test_cannot_create_user_with_duplicate_name(): void
{
$this->artisan('app:create-user', [
'name' => 'ajaxray',
'email' => 'user1@ajaxray.com',
'password' => '111111',
])->assertSuccessful();
$this->artisan('app:create-user', [
'name' => 'ajaxray',
'email' => 'user2@ajaxray.com',
'password' => '222222',
])->assertFailed()
->expectsOutputToContain('name has already been taken.');
$this->assertDatabaseCount('users', 1);
}
public function test_cannot_create_user_with_duplicate_email(): void
{
$this->artisan('app:create-user', [
'name' => 'user1',
'email' => 'user@ajaxray.com',
'password' => '111111',
])->assertSuccessful();
$this->artisan('app:create-user', [
'name' => 'user2',
'email' => 'user@ajaxray.com',
'password' => '222222',
])->assertFailed()
->expectsOutputToContain('email has already been taken.');
$this->assertDatabaseCount('users', 1);
}
public function test_created_users_are_verified_by_default(): void
{
$this->assertDatabaseEmpty('users');
$this->freezeTime(function (Carbon $time) {
$dateTimeStr = date('Y-m-d H:i:s');
$this->artisan('app:create-user', [
'name' => 'user1',
'email' => 'user@ajaxray.com',
'password' => '111111',
])->assertSuccessful();
$this->assertDatabaseHas('users', ['email_verified_at' => $dateTimeStr]);
});
}
public function test_created_users_can_be_kept_unverified(): void
{
$this->assertDatabaseEmpty('users');
$this->artisan('app:create-user', [
'name' => 'user1',
'email' => 'user@ajaxray.com',
'password' => '111111',
'--unverified' => true
])->assertSuccessful();
$this->assertDatabaseHas('users', ['email_verified_at' => null]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment