laravel-prompts
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLaravel Prompts Skill
Laravel Prompts 技能指南
Laravel Prompts is a PHP package for adding beautiful and user-friendly forms to your command-line applications, with browser-like features including placeholder text and validation. It's pre-installed in Laravel and supports macOS, Linux, and Windows with WSL.
Laravel Prompts 是一个PHP包,可为你的命令行应用添加美观且用户友好的表单,具备类浏览器特性,包括占位符文本和验证功能。它已预安装在Laravel中,支持macOS、Linux和带WSL的Windows系统。
When to Use This Skill
何时使用该技能
This skill should be triggered when:
- Building Laravel Artisan commands with interactive prompts
- Creating user-friendly CLI applications in PHP
- Implementing form validation in command-line tools
- Adding text input, select menus, or confirmation dialogs to console commands
- Working with progress bars, loading spinners, or tables in CLI applications
- Testing Laravel console commands with prompts
- Converting simple console input to modern, validated, interactive prompts
在以下场景下应触发该技能:
- 构建带交互式提示的Laravel Artisan命令
- 用PHP创建用户友好的CLI应用
- 在命令行工具中实现表单验证
- 为控制台命令添加文本输入、选择菜单或确认对话框
- 在CLI应用中使用进度条、加载动画或表格
- 测试带提示的Laravel控制台命令
- 将简单的控制台输入转换为现代化、带验证的交互式提示
Quick Reference
快速参考
Basic Text Input
基础文本输入
php
use function Laravel\Prompts\text;
// Simple text input
$name = text('What is your name?');
// With placeholder and validation
$name = text(
label: 'What is your name?',
placeholder: 'E.g. Taylor Otwell',
required: true,
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
}
);php
use function Laravel\Prompts\text;
// Simple text input
$name = text('What is your name?');
// With placeholder and validation
$name = text(
label: 'What is your name?',
placeholder: 'E.g. Taylor Otwell',
required: true,
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
}
);Password Input
密码输入
php
use function Laravel\Prompts\password;
$password = password(
label: 'What is your password?',
placeholder: 'password',
hint: 'Minimum 8 characters.',
required: true,
validate: fn (string $value) => match (true) {
strlen($value) < 8 => 'The password must be at least 8 characters.',
default => null
}
);php
use function Laravel\Prompts\password;
$password = password(
label: 'What is your password?',
placeholder: 'password',
hint: 'Minimum 8 characters.',
required: true,
validate: fn (string $value) => match (true) {
strlen($value) < 8 => 'The password must be at least 8 characters.',
default => null
}
);Select (Single Choice)
单选选择器
php
use function Laravel\Prompts\select;
// Simple select
$role = select(
label: 'What role should the user have?',
options: ['Member', 'Contributor', 'Owner']
);
// With associative array (returns key)
$role = select(
label: 'What role should the user have?',
options: [
'member' => 'Member',
'contributor' => 'Contributor',
'owner' => 'Owner',
],
default: 'owner'
);
// From database with custom scroll
$role = select(
label: 'Which category would you like to assign?',
options: Category::pluck('name', 'id'),
scroll: 10
);php
use function Laravel\Prompts\select;
// Simple select
$role = select(
label: 'What role should the user have?',
options: ['Member', 'Contributor', 'Owner']
);
// With associative array (returns key)
$role = select(
label: 'What role should the user have?',
options: [
'member' => 'Member',
'contributor' => 'Contributor',
'owner' => 'Owner',
],
default: 'owner'
);
// From database with custom scroll
$role = select(
label: 'Which category would you like to assign?',
options: Category::pluck('name', 'id'),
scroll: 10
);Multiselect (Multiple Choices)
多选选择器
php
use function Laravel\Prompts\multiselect;
$permissions = multiselect(
label: 'What permissions should be assigned?',
options: ['Read', 'Create', 'Update', 'Delete'],
default: ['Read', 'Create'],
hint: 'Permissions may be updated at any time.'
);
// With validation
$permissions = multiselect(
label: 'What permissions should the user have?',
options: [
'read' => 'Read',
'create' => 'Create',
'update' => 'Update',
'delete' => 'Delete',
],
validate: fn (array $values) => ! in_array('read', $values)
? 'All users require the read permission.'
: null
);php
use function Laravel\Prompts\multiselect;
$permissions = multiselect(
label: 'What permissions should be assigned?',
options: ['Read', 'Create', 'Update', 'Delete'],
default: ['Read', 'Create'],
hint: 'Permissions may be updated at any time.'
);
// With validation
$permissions = multiselect(
label: 'What permissions should the user have?',
options: [
'read' => 'Read',
'create' => 'Create',
'update' => 'Update',
'delete' => 'Delete',
],
validate: fn (array $values) =>! in_array('read', $values)
? 'All users require the read permission.'
: null
);Confirmation Dialog
确认对话框
php
use function Laravel\Prompts\confirm;
// Simple yes/no
$confirmed = confirm('Do you accept the terms?');
// With custom labels
$confirmed = confirm(
label: 'Do you accept the terms?',
default: false,
yes: 'I accept',
no: 'I decline',
hint: 'The terms must be accepted to continue.'
);
// Require "Yes"
$confirmed = confirm(
label: 'Do you accept the terms?',
required: true
);php
use function Laravel\Prompts\confirm;
// Simple yes/no
$confirmed = confirm('Do you accept the terms?');
// With custom labels
$confirmed = confirm(
label: 'Do you accept the terms?',
default: false,
yes: 'I accept',
no: 'I decline',
hint: 'The terms must be accepted to continue.'
);
// Require "Yes"
$confirmed = confirm(
label: 'Do you accept the terms?',
required: true
);Search (Searchable Select)
搜索选择器(可搜索的单选)
php
use function Laravel\Prompts\search;
$id = search(
label: 'Search for the user that should receive the mail',
placeholder: 'E.g. Taylor Otwell',
options: fn (string $value) => strlen($value) > 0
? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
: [],
hint: 'The user will receive an email immediately.',
scroll: 10
);php
use function Laravel\Prompts\search;
$id = search(
label: 'Search for the user that should receive the mail',
placeholder: 'E.g. Taylor Otwell',
options: fn (string $value) => strlen($value) > 0
? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all()
: [],
hint: 'The user will receive an email immediately.',
scroll: 10
);Suggest (Auto-completion)
自动补全提示
php
use function Laravel\Prompts\suggest;
// Static options
$name = suggest('What is your name?', ['Taylor', 'Dayle']);
// Dynamic filtering
$name = suggest(
label: 'What is your name?',
options: fn ($value) => collect(['Taylor', 'Dayle'])
->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true))
);php
use function Laravel\Prompts\suggest;
// Static options
$name = suggest('What is your name?', ['Taylor', 'Dayle']);
// Dynamic filtering
$name = suggest(
label: 'What is your name?',
options: fn ($value) => collect(['Taylor', 'Dayle'])
->filter(fn ($name) => Str::contains($name, $value, ignoreCase: true))
);Multi-step Forms
多步骤表单
php
use function Laravel\Prompts\form;
$responses = form()
->text('What is your name?', required: true, name: 'name')
->password(
label: 'What is your password?',
validate: ['password' => 'min:8'],
name: 'password'
)
->confirm('Do you accept the terms?')
->submit();
// Access named responses
echo $responses['name'];
echo $responses['password'];
// Dynamic forms with previous responses
$responses = form()
->text('What is your name?', required: true, name: 'name')
->add(function ($responses) {
return text("How old are you, {$responses['name']}?");
}, name: 'age')
->submit();php
use function Laravel\Prompts\form;
$responses = form()
->text('What is your name?', required: true, name: 'name')
->password(
label: 'What is your password?',
validate: ['password' => 'min:8'],
name: 'password'
)
->confirm('Do you accept the terms?')
->submit();
// Access named responses
echo $responses['name'];
echo $responses['password'];
// Dynamic forms with previous responses
$responses = form()
->text('What is your name?', required: true, name: 'name')
->add(function ($responses) {
return text("How old are you, {$responses['name']}?");
}, name: 'age')
->submit();Progress Bar
进度条
php
use function Laravel\Prompts\progress;
// Simple usage
$users = progress(
label: 'Updating users',
steps: User::all(),
callback: fn ($user) => $this->performTask($user)
);
// With dynamic labels
$users = progress(
label: 'Updating users',
steps: User::all(),
callback: function ($user, $progress) {
$progress
->label("Updating {$user->name}")
->hint("Created on {$user->created_at}");
return $this->performTask($user);
},
hint: 'This may take some time.'
);php
use function Laravel\Prompts\progress;
// Simple usage
$users = progress(
label: 'Updating users',
steps: User::all(),
callback: fn ($user) => $this->performTask($user)
);
// With dynamic labels
$users = progress(
label: 'Updating users',
steps: User::all(),
callback: function ($user, $progress) {
$progress
->label("Updating {$user->name}")
->hint("Created on {$user->created_at}");
return $this->performTask($user);
},
hint: 'This may take some time.'
);Loading Spinner
加载动画
php
use function Laravel\Prompts\spin;
$response = spin(
callback: fn () => Http::get('http://example.com'),
message: 'Fetching response...'
);php
use function Laravel\Prompts\spin;
$response = spin(
callback: fn () => Http::get('http://example.com'),
message: 'Fetching response...'
);Key Concepts
核心概念
Input Types
输入类型
Laravel Prompts provides several input types for different use cases:
- text() - Single-line text input with optional placeholder and validation
- textarea() - Multi-line text input for longer content
- password() - Masked text input for sensitive data
- confirm() - Yes/No confirmation dialog
- select() - Single selection from a list of options
- multiselect() - Multiple selections from a list
- suggest() - Text input with auto-completion suggestions
- search() - Searchable single selection with dynamic options
- multisearch() - Searchable multiple selections
- pause() - Pause execution until user presses ENTER
Laravel Prompts 提供多种输入类型以适配不同使用场景:
- text() - 带可选占位符和验证的单行文本输入
- textarea() - 用于长内容的多行文本输入
- password() - 用于敏感数据的掩码文本输入
- confirm() - 是/否确认对话框
- select() - 从选项列表中单选
- multiselect() - 从选项列表中多选
- suggest() - 带自动补全建议的文本输入
- search() - 带动态选项的可搜索单选器
- multisearch() - 可搜索的多选器
- pause() - 暂停执行直到用户按下ENTER键
Output Types
输出类型
For displaying information without input:
- info() - Display informational message
- note() - Display a note
- warning() - Display warning message
- error() - Display error message
- alert() - Display alert message
- table() - Display tabular data
用于无需输入的信息展示:
- info() - 显示信息性消息
- note() - 显示备注信息
- warning() - 显示警告消息
- error() - 显示错误消息
- alert() - 显示警示消息
- table() - 显示表格数据
Validation
验证
Three ways to validate prompts:
-
Closure validation: Custom logic with match expressionsphp
validate: fn (string $value) => match (true) { strlen($value) < 3 => 'Too short.', default => null } -
Laravel validation rules: Standard Laravel validationphp
validate: ['email' => 'required|email|unique:users'] -
Required flag: Simple requirement checkphp
required: true
三种验证提示的方式:
-
闭包验证:使用match表达式的自定义逻辑php
validate: fn (string $value) => match (true) { strlen($value) < 3 => 'Too short.', default => null } -
Laravel验证规则:标准的Laravel验证php
validate: ['email' => 'required|email|unique:users'] -
必填标记:简单的必填项检查php
required: true
Transformation
数据转换
Use the parameter to modify input before validation:
transformphp
$name = text(
label: 'What is your name?',
transform: fn (string $value) => trim($value),
validate: fn (string $value) => strlen($value) < 3
? 'The name must be at least 3 characters.'
: null
);使用参数在验证前修改输入内容:
transformphp
$name = text(
label: 'What is your name?',
transform: fn (string $value) => trim($value),
validate: fn (string $value) => strlen($value) < 3
? 'The name must be at least 3 characters.'
: null
);Terminal Features
终端特性
- Scrolling: Configure visible items with parameter (default: 5)
scroll - Navigation: Use arrow keys, j/k keys, or vim-style navigation
- Forms: Press CTRL + U in forms to return to previous prompts
- Width: Keep labels under 74 characters for 80-character terminals
- 滚动:使用参数配置可见选项数量(默认:5)
scroll - 导航:使用箭头键、j/k键或vim风格导航
- 表单:在表单中按CTRL + U可返回上一个提示
- 宽度:标签长度保持在74字符以内,适配80字符宽度的终端
Reference Files
参考文件
This skill includes comprehensive documentation in :
references/- other.md - Complete Laravel Prompts documentation including:
- All prompt types (text, password, select, search, etc.)
- Validation strategies and examples
- Form API for multi-step input
- Progress bars and loading indicators
- Informational messages (info, warning, error, alert)
- Tables for displaying data
- Testing strategies for console commands
- Fallback configuration for unsupported environments
Use to read the reference file when detailed information is needed.
view该技能在目录下包含完整文档:
references/- other.md - 完整的Laravel Prompts文档,包括:
- 所有提示类型(文本、密码、选择器、搜索器等)
- 验证策略及示例
- 用于多步骤输入的Form API
- 进度条和加载指示器
- 信息性消息(info、warning、error、alert)
- 用于数据展示的表格
- 控制台命令的测试策略
- 不兼容环境的降级配置
当需要详细信息时,使用命令查看参考文件。
viewWorking with This Skill
使用该技能的不同阶段指南
For Beginners
初学者
Start with basic prompts:
- Use for simple input
text() - Add for mandatory fields
required: true - Try for yes/no questions
confirm() - Use for predefined choices
select()
Example beginner command:
php
$name = text('What is your name?', required: true);
$confirmed = confirm('Is this correct?');
if ($confirmed) {
$this->info("Hello, {$name}!");
}从基础提示开始:
- 使用获取简单输入
text() - 为必填字段添加
required: true - 尝试用实现是/否问题
confirm() - 使用处理预定义选项
select()
初学者示例命令:
php
$name = text('What is your name?', required: true);
$confirmed = confirm('Is this correct?');
if ($confirmed) {
$this->info("Hello, {$name}!");
}For Intermediate Users
中级用户
Combine multiple prompts and add validation:
- Use the API for multi-step input
form() - Add custom validation with closures
- Use for database queries
search() - Implement progress bars for long operations
Example intermediate command:
php
$responses = form()
->text('Name', required: true, name: 'name')
->select('Role', options: ['Member', 'Admin'], name: 'role')
->confirm('Create user?')
->submit();
if ($responses) {
progress(
label: 'Creating user',
steps: 5,
callback: fn () => sleep(1)
);
}组合多个提示并添加验证:
- 使用API实现多步骤输入
form() - 通过闭包添加自定义验证
- 使用实现数据库查询
search() - 为长时间操作实现进度条
中级用户示例命令:
php
$responses = form()
->text('Name', required: true, name: 'name')
->select('Role', options: ['Member', 'Admin'], name: 'role')
->confirm('Create user?')
->submit();
if ($responses) {
progress(
label: 'Creating user',
steps: 5,
callback: fn () => sleep(1)
);
}For Advanced Users
高级用户
Leverage advanced features:
- Dynamic form fields based on previous responses
- Complex validation with Laravel validation rules
- Custom searchable prompts with database integration
- Transformation functions for data normalization
- Testing strategies for command prompts
Example advanced command:
php
$responses = form()
->text('Email', validate: ['email' => 'required|email|unique:users'], name: 'email')
->add(function ($responses) {
return search(
label: 'Select manager',
options: fn ($value) => User::where('email', 'like', "%{$value}%")
->where('email', '!=', $responses['email'])
->pluck('name', 'id')
->all()
);
}, name: 'manager_id')
->multiselect(
label: 'Permissions',
options: Permission::pluck('name', 'id'),
validate: fn ($values) => count($values) === 0 ? 'Select at least one permission.' : null,
name: 'permissions'
)
->submit();利用高级特性:
- 根据之前的响应动态生成表单字段
- 使用Laravel验证规则实现复杂验证
- 实现带数据库集成的自定义可搜索提示
- 使用转换函数进行数据标准化
- 命令提示的测试策略
高级用户示例命令:
php
$responses = form()
->text('Email', validate: ['email' => 'required|email|unique:users'], name: 'email')
->add(function ($responses) {
return search(
label: 'Select manager',
options: fn ($value) => User::where('email', 'like', "%{$value}%")
->where('email', '!=', $responses['email'])
->pluck('name', 'id')
->all()
);
}, name: 'manager_id')
->multiselect(
label: 'Permissions',
options: Permission::pluck('name', 'id'),
validate: fn ($values) => count($values) === 0? 'Select at least one permission.' : null,
name: 'permissions'
)
->submit();Navigation Tips
导航技巧
- Arrow keys or j/k - Navigate options in select/multiselect
- Space - Select/deselect in multiselect
- Enter - Confirm selection or submit input
- CTRL + U - Go back to previous prompt (in forms)
- Type to search - In search/multisearch prompts
- Tab - Auto-complete in suggest prompts
- 箭头键或j/k键 - 在单选/多选选择器中导航选项
- 空格键 - 在多选选择器中选择/取消选择
- 回车键 - 确认选择或提交输入
- CTRL + U - 返回上一个提示(在表单中)
- 输入文本 - 在搜索/多搜索提示中进行搜索
- Tab键 - 在自动补全提示中完成补全
Testing
测试
Test commands with prompts using Laravel's built-in assertions:
php
use function Pest\Laravel\artisan;
test('user creation command', function () {
artisan('users:create')
->expectsQuestion('What is your name?', 'Taylor Otwell')
->expectsQuestion('What is your email?', '[email protected]')
->expectsConfirmation('Create this user?', 'yes')
->expectsPromptsInfo('User created successfully!')
->assertExitCode(0);
});
test('displays warnings and errors', function () {
artisan('report:generate')
->expectsPromptsWarning('This action cannot be undone')
->expectsPromptsError('Something went wrong')
->expectsPromptsTable(
headers: ['Name', 'Email'],
rows: [
['Taylor Otwell', '[email protected]'],
['Jason Beggs', '[email protected]'],
]
)
->assertExitCode(0);
});使用Laravel内置的断言测试带提示的命令:
php
use function Pest\Laravel\artisan;
test('user creation command', function () {
artisan('users:create')
->expectsQuestion('What is your name?', 'Taylor Otwell')
->expectsQuestion('What is your email?', '[email protected]')
->expectsConfirmation('Create this user?', 'yes')
->expectsPromptsInfo('User created successfully!')
->assertExitCode(0);
});
test('displays warnings and errors', function () {
artisan('report:generate')
->expectsPromptsWarning('This action cannot be undone')
->expectsPromptsError('Something went wrong')
->expectsPromptsTable(
headers: ['Name', 'Email'],
rows: [
['Taylor Otwell', '[email protected]'],
['Jason Beggs', '[email protected]'],
]
)
->assertExitCode(0);
});Best Practices
最佳实践
Design Guidelines
设计指南
- Keep labels concise (under 74 characters for 80-column terminals)
- Use parameter for additional context
hint - Set appropriate values when sensible
default - Configure for lists with many options (default: 5)
scroll
- 保持标签简洁(80列宽度终端下不超过74字符)
- 使用参数提供额外上下文
hint - 在合理情况下设置合适的值
default - 为选项较多的列表配置参数(默认:5)
scroll
Validation Strategy
验证策略
- Use for mandatory fields
required: true - Apply Laravel validation rules for standard checks (email, min/max, etc.)
- Use closures for complex business logic validation
- Provide clear, actionable error messages
- 为必填字段使用
required: true - 对标准检查(邮箱、最小/最大长度等)应用Laravel验证规则
- 对复杂业务逻辑使用闭包验证
- 提供清晰、可操作的错误消息
User Experience
用户体验
- Add placeholders to show expected input format
- Use before destructive operations
pause() - Show progress bars for operations taking >2 seconds
- Display informational messages after actions complete
- Group related prompts in forms for better flow
- 添加占位符以展示预期输入格式
- 在破坏性操作前使用
pause() - 对耗时超过2秒的操作显示进度条
- 操作完成后显示信息性消息
- 将相关提示分组到表单中以优化流程
Performance
性能
- Use callbacks with length checks to avoid expensive queries:
search()phpoptions: fn (string $value) => strlen($value) > 0 ? User::where('name', 'like', "%{$value}%")->pluck('name', 'id')->all() : [] - Limit database results with pagination or top-N queries
- Cache frequently-accessed option lists
- Use for HTTP requests and long operations
spin()
- 使用带长度检查的回调避免昂贵的查询:
search()phpoptions: fn (string $value) => strlen($value) > 0 ? User::where('name', 'like', "%{$value}%")->pluck('name', 'id')->all() : [] - 使用分页或前N条查询限制数据库结果
- 缓存频繁访问的选项列表
- 对HTTP请求和长时间操作使用
spin()
Common Patterns
常见模式
User Registration Flow
用户注册流程
php
$responses = form()
->text('Name', required: true, name: 'name')
->text('Email', validate: ['email' => 'required|email|unique:users'], name: 'email')
->password('Password', validate: ['password' => 'required|min:8'], name: 'password')
->submit();php
$responses = form()
->text('Name', required: true, name: 'name')
->text('Email', validate: ['email' => 'required|email|unique:users'], name: 'email')
->password('Password', validate: ['password' => 'required|min:8'], name: 'password')
->submit();Confirmation Before Destructive Action
破坏性操作前的确认
php
$confirmed = confirm(
label: 'Are you sure you want to delete all users?',
default: false,
hint: 'This action cannot be undone.'
);
if (! $confirmed) {
$this->info('Operation cancelled.');
return;
}php
$confirmed = confirm(
label: 'Are you sure you want to delete all users?',
default: false,
hint: 'This action cannot be undone.'
);
if (! $confirmed) {
$this->info('Operation cancelled.');
return;
}Dynamic Multi-step Form
动态多步骤表单
php
$responses = form()
->select('User type', options: ['Regular', 'Admin'], name: 'type')
->add(function ($responses) {
if ($responses['type'] === 'Admin') {
return password('Admin password', required: true);
}
}, name: 'admin_password')
->submit();php
$responses = form()
->select('User type', options: ['Regular', 'Admin'], name: 'type')
->add(function ($responses) {
if ($responses['type'] === 'Admin') {
return password('Admin password', required: true);
}
}, name: 'admin_password')
->submit();Batch Processing with Progress
带进度条的批量处理
php
$items = Item::all();
$results = progress(
label: 'Processing items',
steps: $items,
callback: function ($item, $progress) {
$progress->hint("Processing: {$item->name}");
return $this->process($item);
}
);php
$items = Item::all();
$results = progress(
label: 'Processing items',
steps: $items,
callback: function ($item, $progress) {
$progress->hint("Processing: {$item->name}");
return $this->process($item);
}
);Resources
资源
Official Documentation
官方文档
- Laravel Prompts Documentation: https://laravel.com/docs/12.x/prompts
- Laravel Console Testing: https://laravel.com/docs/12.x/console-tests
- Laravel Prompts 文档:https://laravel.com/docs/12.x/prompts
- Laravel 控制台测试:https://laravel.com/docs/12.x/console-tests
Platform Support
平台支持
- Supported: macOS, Linux, Windows with WSL
- Fallback: Configure fallback behavior for unsupported environments
- 支持的平台:macOS、Linux、带WSL的Windows
- 降级方案:为不兼容环境配置降级行为
Notes
注意事项
- Laravel Prompts is pre-installed in Laravel framework
- Supports Laravel validation rules for easy integration
- Uses terminal control codes for interactive UI
- All prompts return values that can be used immediately
- Forms support revisiting previous prompts with CTRL + U
- Validation runs on every input change for immediate feedback
- Progress bars can be manually controlled or automated
- Laravel Prompts 已预安装在Laravel框架中
- 支持Laravel验证规则,便于集成
- 使用终端控制代码实现交互式UI
- 所有提示都会返回可直接使用的值
- 表单支持通过CTRL + U返回上一个提示
- 验证会在每次输入变化时运行,提供即时反馈
- 进度条可手动控制或自动运行
Updating
更新说明
This skill was generated from the official Laravel Prompts documentation. To refresh with updated information, re-scrape the Laravel documentation site.
该技能基于官方Laravel Prompts文档生成。如需更新信息,请重新爬取Laravel文档网站内容。