Laravel Prompts는 커맨드라인 애플리케이션에 아름답고 사용하기 쉬운 대화형 폼을 추가하기 위한 PHP 패키지입니다.
플레이스홀더 텍스트나 검증 등 브라우저의 폼에 가까운 경험을 제공합니다.Artisan 명령 코드 내에서 직접 호출할 수 있으므로, 사용자에 대한 문의를 단순하고 직관적으로 기술할 수 있습니다.
use function Laravel\Prompts\text;$name = text('What is your name?');
플레이스홀더·기본값·힌트를 설정할 수 있습니다.
$name = text( label: 'What is your name?', placeholder: 'E.g. Taylor Otwell', default: $user?->name, hint: 'This will be displayed on your profile.');
required를 지정하면 입력을 필수로 만들 수 있습니다. 검증 메시지도 변경 가능합니다.
$name = text( label: 'What is your name?', required: 'Your name is required.');
validate 클로저로 추가 검증을 수행할 수 있습니다. 에러 메시지를 반환하거나, 합격 시에 null을 반환합니다.
$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 });
Laravel의 검증 규칙을 배열로 지정할 수도 있습니다.
$name = text( label: 'What is your name?', validate: ['name' => 'required|max:255|unique:users']);
use function Laravel\Prompts\number;$copies = number( label: 'How many copies would you like?', default: 1, validate: ['copies' => 'required|integer|min:1|max:100']);
use function Laravel\Prompts\password;$password = password('What is your password?');
$password = password( label: 'What is your password?', placeholder: 'password', hint: 'Minimum 8 characters.', validate: fn (string $value) => strlen($value) < 8 ? 'The password must be at least 8 characters.' : null);
confirm()으로 사용자에게 양자택일 확인을 요구합니다. true 또는 false를 반환합니다.
use function Laravel\Prompts\confirm;$confirmed = confirm('Do you accept the terms?');
기본값이나 라벨 텍스트를 커스터마이즈할 수 있습니다.
$confirmed = confirm( label: 'Do you accept the terms?', default: false, yes: 'I accept', no: 'I decline', hint: 'The terms must be accepted to continue.');
use function Laravel\Prompts\select;$role = select( label: 'What role should the user have?', options: ['Member', 'Contributor', 'Owner'], default: 'Owner');
연관 배열을 사용하면 표시 라벨이 아닌 키를 반환값으로 만들 수 있습니다.
$role = select( label: 'What role should the user have?', options: [ 'member' => 'Member', 'contributor' => 'Contributor', 'owner' => 'Owner', ], default: 'owner');
scroll로 스크롤 전에 표시할 선택지 수를 변경할 수 있습니다(기본값 5개).
$role = select( label: 'Which category would you like to assign?', options: Category::pluck('name', 'id'), scroll: 10);
use function Laravel\Prompts\multiselect;$permissions = multiselect( label: 'What permissions should be assigned?', options: ['Read', 'Create', 'Update', 'Delete']);
required를 지정하면 최소 하나의 선택을 필수로 만들 수 있습니다.
$permissions = multiselect( label: 'What permissions should be assigned?', options: ['Read', 'Create', 'Update', 'Delete'], required: 'At least one permission must be selected.');
search()는 입력할 때마다 후보 리스트를 갱신합니다. 클로저가 반환하는 배열이 후보가 됩니다.
use function Laravel\Prompts\search;$userId = search( label: 'Search for the user that should receive the mail', options: fn (string $value) => strlen($value) > 0 ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() : []);
use function Laravel\Prompts\multisearch;$userIds = multisearch( label: 'Search for the users that should receive the mail', options: fn (string $value) => strlen($value) > 0 ? User::whereLike('name', "%{$value}%")->pluck('name', 'id')->all() : []);
$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 });
클로저가 문자열을 반환하면 에러로 표시하고 재입력을 재촉합니다. null을 반환하면 검증 성공입니다.Laravel의 검증 규칙을 배열 형식으로 사용할 수도 있습니다.
$name = text( label: 'What is your name?', validate: ['name' => 'required|max:255|unique:users']);
입력을 검증 전에 변환하려면 transform 인수를 사용합니다.
$name = text( label: 'What is your name?', transform: fn (string $value) => trim($value), validate: fn (string $value) => match (true) { strlen($value) === 0 => 'The name must not be empty.', default => null });
form()을 사용하면 여러 프롬프트를 하나로 묶어, 완료 전에 통째로 취소할 수 있습니다.
use function Laravel\Prompts\form;$responses = form() ->text('What is your name?', required: true, name: 'name') ->password('What is your password?', validate: ['password' => 'min:8'], name: 'password') ->confirm('Do you accept the terms?') ->submit();$name = $responses['name'];$password = $responses['password'];$confirmed = $responses[2];
use function Laravel\Prompts\info;use function Laravel\Prompts\warning;use function Laravel\Prompts\error;use function Laravel\Prompts\alert;use function Laravel\Prompts\note;note('Prepare for launch.');info('User created successfully.');warning('This action cannot be undone.');error('Something went wrong.');alert('Critical failure detected!');
callout()은 라벨과 콘텐츠를 테두리로 감싸서 표시합니다. 배포 요약, 에러 상세, 상태 갱신 등, 중요한 정보를 두드러지게 하는 데 적합합니다.
use function Laravel\Prompts\callout;callout( label: 'Environment Configured', content: 'Your application is running in production mode with 4 workers.',);
type 인수에 'warning' 또는 'error'를 지정하면 비주얼 스타일을 변경할 수 있습니다.
callout( label: 'Deprecation Notice', content: 'The `--prefer-stable` flag will be removed in v4.0.', type: 'warning',);callout( label: 'Database Connection Failed', content: 'Could not connect to MySQL on 127.0.0.1:3306.', type: 'error',);
info 인수로 푸터 행을 추가할 수 있습니다. ID나 타임스탬프 등의 메타데이터 표시에 편리합니다.
callout( label: 'Deployment Summary', content: 'Your application was deployed to production.', info: 'deploy-id: d4f8a2c',);
문자열 대신 배열을 전달하면 구조화된 리치 콜아웃을 만들 수 있습니다. Element 클래스에는 헤딩·불릿 리스트·번호 리스트·키-값 리스트·링크를 만드는 팩토리 메서드가 있습니다.
use Laravel\Prompts\Elements\Element;use function Laravel\Prompts\callout;callout('Deployment Summary', [ 'Your application was deployed to production at 2024-03-15 14:32 UTC.', Element::heading('What Changed'), Element::bulletedList([ 'Migrated 3 pending database migrations', 'Cleared and rebuilt route cache', 'Restarted 4 queue workers', ]), Element::heading('Next Steps'), Element::numberedList([ 'Verify the health check endpoint at /up', 'Monitor error rates for the next 15 minutes', 'Confirm background jobs are processing', ]),]);
Element::keyValueList로 라벨 첨부 데이터를 표시할 수 있습니다.
callout('Database Connection Failed', [ 'Could not connect to the database server.', Element::keyValueList([ 'Host' => '127.0.0.1', 'Port' => '3306', 'Database' => 'forge', 'Status' => 'Connection refused', ]),], type: 'error');
Element::link는 OSC 8에 대응한 터미널에서 클릭 가능한 하이퍼링크를 생성합니다. URL만, 또는 URL과 커스텀 라벨을 전달할 수 있습니다.
callout('Server Health Check', [ 'Multiple services are reporting degraded performance.', Element::heading('Affected Services'), 'Look here: '.Element::link('https://example.com/health', 'Health Dashboard'), Element::link('https://example.com/health'),]);
use function Laravel\Prompts\progress;$users = progress( label: 'Updating users', steps: User::all(), callback: fn ($user) => $this->performTask($user), hint: 'This may take some time.');
use function Laravel\Prompts\stream;$stream = stream();foreach ($words as $word) { $stream->append($word . ' '); usleep(25_000); // 청크 간 지연을 시뮬레이트...}$stream->close();
append 메서드는 페이드 인 이펙트로 텍스트를 스트림에 추가합니다. 모든 콘텐츠를 스트리밍하고 나면 close를 호출해 출력을 확정하고 커서를 복원합니다.
터미널 폭: 라벨·선택지·검증 메시지가 터미널의 열수를 넘는 경우 자동으로 잘립니다. 80열의 터미널을 상정하는 경우 최대 74문자를 기준으로 해 주세요.터미널의 높이: scroll 인수를 받는 프롬프트에서는, 검증 메시지용 스페이스를 포함해 터미널의 높이에 들어가도록 자동으로 값이 조정됩니다.
use Laravel\Prompts\Prompt;Prompt::fake(['Taylor', true]);$name = text('What is your name?');$confirmed = confirm('Do you accept the terms?');Prompt::assertOutputContains('What is your name?');
Laravel의 Artisan 테스트 헬퍼를 사용하면 정보 출력 함수에 대해서도 어서션을 기술할 수 있습니다.
// Pesttest('report generation', function () { $this->artisan('report:generate') ->expectsPromptsInfo('Welcome to the application!') ->expectsPromptsWarning('This action cannot be undone') ->expectsPromptsError('Something went wrong') ->expectsPromptsAlert('Important notice!') ->expectsPromptsTable( headers: ['Name', 'Email'], rows: [ ['Taylor Otwell', '[email protected]'], ] ) ->assertExitCode(0);});
// PHPUnitpublic function test_report_generation(): void{ $this->artisan('report:generate') ->expectsPromptsInfo('Welcome to the application!') ->expectsPromptsWarning('This action cannot be undone') ->expectsPromptsTable( headers: ['Name', 'Email'], rows: [['Taylor Otwell', '[email protected]']] ) ->assertExitCode(0);}