How to Create Artisan Commands in Laravel


🔧 Why Create Users via Artisan Commands?

Before jumping into code, you might ask — why would I need to create users using an Artisan command when Laravel provides registration forms and seeders?

Here are some great reasons:

  • 🔒 Admin-Only Account Creation: Set up superadmin or staff users directly from the terminal.
  • ⚙️ Automated Deployments: Quickly create or recreate users after database resets.
  • 🔁 Testing & QA: Automate the process of adding users during tests.
  • 🧪 Manual Bypass: In development, you can skip UI entirely and use Artisan to test user flows.

📦 Step 1: Create a Laravel Project (If Needed)

If you don’t already have a Laravel project, you can create one using:

composer create-project laravel/laravel artisan-user-command
cd artisan-user-command

Make sure your .env file is configured properly to connect to your database, and then run:

php artisan migrate

This will create the default tables, including the users table.


🚀 Step 2: Generate a Custom Artisan Command

Laravel offers a built-in Artisan command to create your own commands:

php artisan make:command CreateUser

This will generate a file at:

app/Console/Commands/CreateUser.php

Let’s customize it.


🛠️ Step 3: Customize the Command Signature

Open CreateUser.php and you’ll see a class extending Laravel’s base Command class.

Update the properties:

protected $signature = 'user:create 
                        {--name= : The name of the user} 
                        {--email= : The email of the user} 
                        {--password= : The password for the user}';

protected $description = 'Create a new user from the command line';

Here’s what this does:

  • user:create: The command name
  • --name, --email, --password: Options passed via the terminal

🧠 Step 4: Add User Creation Logic

Inside the handle() method, we’ll retrieve the input values, validate them, and create a user.

Here’s the full method:

public function handle()
{
    $name = $this->option('name') ?? $this->ask('Enter name');
    $email = $this->option('email') ?? $this->ask('Enter email');
    $password = $this->option('password') ?? $this->secret('Enter password');

    // Basic email validation
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $this->error('Invalid email address.');
        return 1;
    }

    // Check if user exists
    if (\App\Models\User::where('email', $email)->exists()) {
        $this->error('A user with this email already exists.');
        return 1;
    }

    // Create user
    $user = \App\Models\User::create([
        'name' => $name,
        'email' => $email,
        'password' => bcrypt($password),
    ]);

    $this->info("User {$user->email} created successfully.");
    return 0;
}

Let’s break this down:

  • We accept input via command-line options or interactive prompts
  • Validate email format
  • Prevent duplicate users
  • Encrypt the password using bcrypt()
  • Save the user to the database

📄 Step 5: Make Sure the User Model is Configured

Open app/Models/User.php and ensure the fields are fillable:

protected $fillable = [
    'name',
    'email',
    'password',
];

This allows mass assignment when creating the user.


🧪 Step 6: Test Your Command

Now you can run the command from the terminal:

php artisan user:create --name="Jane Doe" --email="[email protected]" --password="secret123"

Or let it prompt you interactively:

php artisan user:create

Example:

Enter name: John Smith
Enter email: [email protected]
Enter password:
User [email protected] created successfully.

Check the database, and you’ll see the user entry created.


🧹 Optional: Add Role Support (Advanced)

If your app has roles (e.g., using spatie/laravel-permission), you can easily extend the command:

Update your signature:

protected $signature = 'user:create 
                        {--name=} 
                        {--email=} 
                        {--password=} 
                        {--role= : Assign a role to the user}';

Inside handle():

$role = $this->option('role');

if ($role) {
    $user->assignRole($role);
    $this->info("Assigned role: $role");
}

🗓️ Bonus: Schedule Command to Create Default User

You can schedule this command to run on deployment or weekly by adding it to the app/Console/Kernel.php:

protected function schedule(Schedule $schedule)
{
    $schedule->command('user:create --name=Admin [email protected] --password=admin123')
        ->weekly();
}

Make sure you’ve set up your server cron job to call the scheduler:

* * * * * php /path-to-your-project/artisan schedule:run >> /dev/null 2>&1

🧪 Writing a Test for the Command

You can write tests to validate the command works correctly.

Create a feature test:

php artisan make:test CreateUserCommandTest

Then add:

public function test_it_creates_a_user_via_command()
{
    $this->artisan('user:create', [
        '--name' => 'Test User',
        '--email' => '[email protected]',
        '--password' => 'password123'
    ])
    ->expectsOutput('User [email protected] created successfully.')
    ->assertExitCode(0);

    $this->assertDatabaseHas('users', [
        'email' => '[email protected]'
    ]);
}

Run your test with:

php artisan test

💡 Best Practices

  • Encrypt passwords securely — use Laravel’s bcrypt() or Hash::make().
  • Validate input properly — don’t trust raw CLI inputs.
  • Avoid hardcoding sensitive values — consider .env or secret prompts.
  • Log command execution — for audit purposes in production.
  • Use command arguments or options — don’t rely only on prompts.
  • Make your commands descriptive and safe — especially if used in production.

🧰 Other Useful Artisan Command Examples

  • Create a batch of dummy users: php artisan make:command GenerateTestUsers
  • Reset user passwords: php artisan user:reset-password [email protected] --password=newpass123
  • Deactivate users who haven’t logged in: php artisan user:deactivate-inactive

✅ Conclusion

Creating Artisan commands in Laravel gives you an incredible level of power, automation, and convenience. Whether you’re setting up admin accounts, automating deployments, or generating reports, Artisan lets you write code once and reuse it infinitely — all from the command line.

In this tutorial, you’ve learned how to:

  • Generate a custom Artisan command
  • Accept and validate user input
  • Create users programmatically
  • Add interactive prompts and optional flags
  • Extend commands for advanced logic like roles
  • Schedule and test your command

Once you understand how Artisan works, you’ll be able to build your own robust developer tooling right inside your Laravel app.


Now it’s your turn!
Try building a command like user:reset-password or user:promote-admin to further automate your application tasks.


Leave a Reply

Your email address will not be published. Required fields are marked *