I’ve been working on a package called Laravel Console, which provides a bunch of enhancements on top of Laravel Console Commands.
Version 1.2.0 has now been released. 😃
Whats New?
A new Trait (Concern in Laravel’s terms) has been added called AskAndValidate. When added to your commands provides the ability to ask a question and validate input, but the best bit is that it will continuously prompt the user until the validation passes.
I stared to write this feature and then thought it might be better in Laravel. So I opened a Pull Request. Sadly it didn’t work out so I’ve finished it off and kept it in my package.
How Do I Use It
Simply add the trait SmashedEgg\LaravelConsole\Concerns\AskAndValidate
to your existing commands. Adding this trait provides a new method askAndValidate
.
You don't have to extend SmashedEgg\LaravelConsole\Command
to use this feature.
With this trait you 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:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use SmashedEgg\LaravelConsole\Concerns\AskAndValidate;
class AgeCommand extends Command
{
use AskAndValidate;
protected $signature = 'ask-age';
public function handle()
{
$age = $this->askAndValidate(question: 'Age ?', rules: ['integer'], messages: ['input.integer' => 'Input must be a number']);
$this->info('You are ' . $age);
return 0;
}
}
The user will be prompted in a loop until the age is entered correctly.
vagrant@homestead:/var/www/vhosts/laravel$ php artisan ask-age
Age ?:
> not an age
Invalid input:
Input must be a number
Age ?:
> 36
You are 36
vagrant@homestead:/var/www/vhosts/laravel$
You can configure the rules and message the Validator should use under the hood.
Caveat. When overriding the error messages the input name must always be input. e.g
messages: ['input.integer' => 'Input must be a number']
Conclusion
This update provides a new feature that should be found useful. It should reduce the amount of code used in a command while also keeping it readable and easy to maintain.
Feedback always welcome.