Create a fancy input for your Laravel Commands

Create a fancy input for your Laravel Commands

ยท

2 min read

Hey guys,

Let's do some hands-on practice today. Gonna show you how to create a fancy input for your command.

Life is too short to do boring things, isn't it? Hehe.

The Fancy and the normal Inputs

When using $this->ask('Give me your freaking input'), it will show up an input like this:

That's a normal one, Laravel doesn't document the way to create a fancy input, like when we run the make:model without any arguments:

(sorry, can't take a picture via ray.so, copy things there and it's break haha)

As we can see, the fancy input has a proper border (which is nice), a placeholder text for examples.

On the other hand, if we press the cancel command (Mac: Command + C | Linux: Control + C), we'll see this message:

And the normal ask:

It's definitely way better than the normal one, right?

How do you implement the Fancy Inputs for Laravel Command?

There are some adjustments we need to make. Let's roll.

Implements PromptsForMissingInput

So that Laravel can smell the missing required arguments thus showing up the inputs for us ๐Ÿ˜‰

Use $name, not $signature

Instead of using $signature, we'll need to use $name (pure form without any options or arguments defined)

class MyFancyCommand extends Command implements PromptsForMissingInput
{
    protected $name = 'app:handle-my-fancy-command';
}

Define Inputs

We'll need to override the getArguments and the promptForMissingArgumentsUsing methods:

// define argument(s) of your command
protected function getArguments(): array
{
    return [
        ['name', InputArgument::REQUIRED, 'Full Name'],
    ];
}

// define the input's label & placeholder text
protected function promptForMissingArgumentsUsing(): array
{
    return [
        'name' => [
            'Can you plz give me your full name?',
            'E.g.: Seth Chen',
        ],
    ];
}

(Optional) Define your Optional parameter(s)

Simply override the getOptions method:

protected function getOptions()
{
    return [
        [
            'admin', // full-form: --admin
            'a',  // short-form: -a
            InputOption::VALUE_NONE, // boolean, no input
            'Make this user as an Administrator', // description
        ],
    ];
}

For InputOption, take the reference here:

(yes I love light mode ๐Ÿ˜ˆ)

Testing

Now, let's hit the app:handle-my-fancy-command and try it out:

Really awesome, isn't it?

What if my terminal can't show up inputs?

This is a fair question, we can't expect all machines (especially servers) to show up fancy things.

Simply use normal arguments or optional parameters without any issue ๐Ÿ˜Ž.

Final Words

From the way we define the arguments & optional parameters, I feel like this is a better way for Laravel commands.

Putting too much text inside the $signature aren't so cool.

Enjoy and happy weekend! ๐Ÿ˜Ž

ย