Adding a Custom Artisan Command (with Optional Arguments)

In this tutorial, we will explore how to create a custom Artisan command in Laravel that allows a command-line user to create a new user.

Our custom command will support parameters to pass username, email, and password and admin yes/no. When not present the command will prompt the user to enter them.

By following the step-by-step instructions and code samples provided, you will be able to create a versatile custom Artisan command to quickly add a user. Let’s get started!

Step 1: Generate the Custom Command

To begin, open your terminal and navigate to your Laravel project’s root directory. Next, run the following command to generate a new custom Artisan command class:

php artisan make:command CreateUserCommand

This command will create a CreateUserCommand class inside the app/Console/Commands directory of your Laravel project.

Step 2: Implement the Command Logic

Open your preferred code editor and navigate to the generated class located at app/Console/Commands/CreateUserCommand.php. In this file, you will find the handle method, where we can define the logic for our custom command. Replace the existing code within the handle method with the following:

app/Console/Commands/CreateUserCommand .php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;

class CreateUserCommand extends Command
{
    protected $signature = 'create:user {username?} {email?} {password?} {--admin : Create an admin user}';

    protected $description = 'Create a new user';

    public function handle()
    {
        $username = $this->argument('username') ?? $this->ask('Enter username:');
        $email = $this->argument('email') ?? $this->ask('Enter email:');
        $password = $this->argument('password') ?? $this->secret('Enter password:');
        $isAdmin = $this->option('admin');

        $user = new User();
        $user->name = $username;
        $user->email = $email;
        $user->password = bcrypt($password);
        $user->is_admin = $isAdmin;
        $user->save();

        $this->info('User created successfully!');
    }
}

In the updated code above, we have modified the signature property to include optional command arguments for username, email, and password. These arguments are enclosed in curly brackets {} and suffixed with a ?. Inside the handle method, we retrieve the values of these arguments using the argument method. If an argument is not provided through the command line, we prompt the user for input using the ask or secret methods, depending on whether the input should be visible or hidden. The --admin flag remains the same as before, allowing the creation of an admin user.

Step 3: Running the Command

With our custom command and its dynamic input in place, we can now run it through the Artisan console. Open your terminal and run the following command:

php artisan create:user

If you provide values for username, email, and password as command line arguments, they will be used directly. Otherwise, the command will prompt you for input. Additionally, you can include the --admin flag to create an admin user.

Example Usages:

  • Running the command with command line arguments:
php artisan create:user john john@example.com password123 --admin
  • Running the command without command line arguments (interactive prompt):
php artisan create:user

Note that if you would like to run the example, you will need to add a column called ‘is_admin’ to Laravel’s default users table. We have introduced this property to the User Model to illustrate the usefulness of a command-line option like --admin in our example.

Conclusion

Congratulations! You have successfully created a custom Artisan command in Laravel that supports dynamic input through command line arguments or interactive prompts. This flexibility enables you to conveniently create users with varying attributes based on your specific needs.

Feel free to explore further customization possibilities and adapt this approach to other scenarios in your projects. Happy coding!

References

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

Leave a Reply

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

Recent Posts