Validating Laravel Prompts Using Built-in Validation
Laravel Prompts was released last month at Laracon US (the recording is also available here). It looks so beautiful and I was keen to try it.
Now that it is released publicly, I am experimenting with Laravel Prompts for a new web application that I am planning to build. The only gripe that I have with it is that validating user inputs can be very tedious. The example given in the official documentation looks like this:
$name = text(
label: 'What is your name?',
validate: fn (string $value) => match (true) {
strlen($value) < 3 => 'The name must be at least 3 characters.',
strlen($value) > 255 => 'The name must not exceed 255 characters.',
default => null
}
);
But it doesn’t have to be that way. We can utilize the Validator
facade to handle the validation for us. For my use case, I created a new private method in the same command class that I have since I am only using it there. Of course, you can further extract the method to a dedicated helper function if needed.
use Illuminate\Support\Facades\Validator;
...
private function validate($value, $name, $rules, $messages = [], $attributes = [])
{
return Validator::make([$name => $value], [$name => $rules], $messages, $attributes)
->errors()
->first($name);
}
The method signature is almost identical to what Validator::make
accepts, so you can still override the attributes name and validation messages if needed. The same code block above can now be refactored to:
$name = text(
label: 'What is your name?',
validate: fn (string $value) => $this->validate($value, 'name', 'min:3|max:255')
);
Now, you have access to all the available validation rules at your disposal to be used in your new, shiny prompts. Happy coding!