Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Add support to ask and validate input in console commands #47813

Closed
wants to merge 5 commits into from

Conversation

tomgrohl
Copy link

When running commands that require a lot of input from the user, if you get partway through and the input is incorrect in some way, you may have to run the command again (depending on how the command is written to handle bad input).

It would be nice to ask for input and validate in a loop until the value is correct. The resulting code makes commands easy to read by combining the input and checking logic.

Example code below:

public function handle()
{
    $name = $this->askAndValidate(question: 'Name ?', rules: ['required', 'string', 'max:25']);

    $this->info('Hello ' . $name);

    return 0;
}

You can even override messages too:

$name = $this->askAndValidate(question: 'Name ?', rules: ['required', 'string', 'max:25'], messages: ['input.required' => 'input is required']);

In the askAndValidate method the user will be prompted in a loop until the validation passes. The Validator facade is used to make and validate the input from the user.

Caveats

There is 1 caveat with the validation part, as thats when adding custom error messages, the field name can only be input. Not sure of an alternative to tackle this.

@tomgrohl
Copy link
Author

The 1 failure doesn't relate to this PR

1) Illuminate\Tests\Support\SleepTest::testItSleepsForSecondsWithMilliseconds
Failed asserting that 1.5306618213653564 matches expected 1.5.

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If possible, please consider releasing your code as a package so that the community can still take advantage of your contributions!

If you feel absolutely certain that this code corrects a bug in the framework, please "@" mention me in a follow-up comment with further explanation so that GitHub will send me a notification of your response.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants