Modernizing Terminal Interfaces with Laravel Prompts
Elevating the CLI Experience
Prerequisites & Tools
To get started, you should have a functional handle() method of your command classes. The core library is laravel/prompts, which provides the functional API used throughout this guide.
Implementation Walkthrough
Using the text function creates a clean input field. Unlike the standard ask method, text supports advanced metadata like placeholders and hints.
use function Laravel\Prompts\text;
$name = text(
label: 'What is the backup name?',
placeholder: 'e.g. daily_backup',
hint: 'This will be the filename suffix.',
required: true
);
For more complex interactions, the multiselect function allows users to toggle multiple options using the spacebar, returning an array of selected values. This is perfect for defining backup scopes like databases, files, or media assets.
use function Laravel\Prompts\multiselect;
$categories = multiselect(
label: 'What should we include?',
options: ['Database', 'Files', 'Media'],
default: ['Database']
);
Input Validation and Defaults
Reliable CLI tools must prevent bad data. Laravel Prompts allows you to pass a closure to the validate parameter. If the logic returns a string, the CLI displays it as a red error message, keeping the user in the prompt until they provide valid data. Combining this with default values—such as a timestamped string—drastically reduces the friction for end-users running routine tasks.
Tips and Best Practices
Always use named arguments to keep your prompt definitions readable. When building tools for other developers, leverage the hint parameter to explain specific requirements, such as character limits or file formats. This documentation-in-terminal approach reduces the need for external manuals and prevents "trial and error" execution.
