Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Prompts Laravel Package

moox/prompts

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require moox/prompts
    

    Register the service provider in config/app.php under providers:

    Moox\Prompts\PromptsServiceProvider::class,
    
  2. First Use Case: Create a simple CLI command with a single prompt:

    php artisan make:command TestPromptCommand
    

    Update the generated command:

    use Moox\Prompts\Support\FlowCommand;
    use function Moox\Prompts\text;
    
    class TestPromptCommand extends FlowCommand
    {
        protected $signature = 'test:prompt';
        protected $description = 'Test a simple prompt';
    
        public ?string $name = null;
    
        public function handle(): void
        {
            $this->name = text(label: 'What is your name?', validate: fn($name) => filled($name));
            $this->info("Hello, {$this->name}!");
        }
    }
    

    Run it:

    php artisan test:prompt
    
  3. Where to Look First:

    • README for core concepts.
    • src/Support/FlowCommand.php for base class details.
    • src/Prompts/ for available prompt types (e.g., text.php, select.php).

Implementation Patterns

Core Workflow: CLI-to-Web Flow

  1. Define a Flow Command: Extend FlowCommand and declare steps in promptFlowSteps().

    class SetupCommand extends FlowCommand
    {
        public ?string $projectName;
        public ?string $environment;
    
        public function promptFlowSteps(): array
        {
            return ['stepProjectName', 'stepEnvironment', 'stepConfirm'];
        }
    }
    
  2. Step-by-Step Prompts: Each step method should:

    • Use text(), select(), confirm(), etc., from Moox\Prompts\.
    • Store responses in public properties (auto-persisted for web flows).
    public function stepProjectName(): void
    {
        $this->projectName = text(
            label: 'Project name:',
            validate: fn($name) => strlen($name) > 3
        );
    }
    
  3. Web Integration:

    • The package auto-handles web flow persistence via session.
    • Steps render as HTML forms with hidden fields for persisted state.
    • Example route:
      Route::get('/setup', [SetupCommand::class, 'webHandle']);
      
  4. Conditional Logic: Use if checks to skip steps or alter prompts based on prior responses:

    public function stepEnvironment(): void
    {
        if ($this->projectName === 'admin') {
            $this->environment = 'production';
            $this->info('Admin project: defaulting to production.');
        } else {
            $this->environment = select(
                label: 'Environment:',
                options: ['staging', 'production', 'local']
            );
        }
    }
    
  5. Validation: Leverage Laravel’s validation rules or closures:

    $this->projectName = text(
        label: 'Project name:',
        validate: fn($name) => [
            'required',
            'string',
            'max:50',
            fn($attr, $value, $fail) => strlen($value) > 3 || $fail('Too short!')
        ]
    );
    
  6. Multi-Step Forms: For complex flows, group prompts into logical steps:

    public function stepDatabase(): void
    {
        $this->databaseHost = text(label: 'Host:');
        $this->databaseName = text(label: 'Database name:');
        $this->databaseUser = text(label: 'Username:');
    }
    

Gotchas and Tips

Pitfalls

  1. State Persistence:

    • Public properties must be initialized (e.g., public ?string $var = null).
    • Non-nullable properties will break web flows. Avoid:
      public string $name; // ❌ Fails if not set in first step.
      
  2. Web Flow Quirks:

    • CSRF Protection: Ensure your web routes include @csrf in forms.
    • Session Timeout: Long flows may hit session timeouts. Extend session lifetime in app/Http/Middleware/StartSession.php:
      public function getSession(): Session
      {
          $session = parent::getSession();
          $session->setTimeout(3600); // 1 hour
          return $session;
      }
      
    • Back Button: Web flows don’t natively support "back" navigation. Use hidden inputs or query params to track progress manually.
  3. Prompt API Mismatches:

    • The CLI and web APIs are not identical. Test both environments:
      // CLI-only: Uses Symfony Style
      $this->error('This won’t work in web!');
      
      // Web-safe: Use $this->line() or $this->info() instead.
      
  4. Validation Feedback:

    • Web prompts show validation errors, but CLI prompts use Symfony’s validator. For consistency, use the same validation logic in both:
      // CLI: Shows "The name field is required."
      // Web: Shows "name: The name field is required."
      
  5. Step Order:

    • promptFlowSteps() order matters. Reordering steps requires updating all references (e.g., conditional logic).

Debugging Tips

  1. Inspect State: Dump persisted state in a step to verify data:

    public function stepDebug(): void
    {
        $this->line(print_r(get_object_vars($this), true));
    }
    
  2. Web Flow Debugging:

    • Check the session for persisted data:
      $this->line(session()->all());
      
    • Verify hidden inputs in generated HTML:
      <input type="hidden" name="_moox_prompt_state" value="...">
      
  3. Prompt-Specific Issues:

    • Select Prompts: Ensure options is an array of strings or Option objects.
    • Confirm Prompts: Default to false for destructive actions:
      $this->deleteDatabase = confirm(
          label: 'Delete database?',
          default: false
      );
      

Extension Points

  1. Custom Prompt Types: Extend Moox\Prompts\Prompt to create reusable prompts:

    class EmailPrompt extends Prompt
    {
        public function __invoke(string $label, array $options = []): string
        {
            return text($label, [
                'validate' => fn($email) => filter_var($email, FILTER_VALIDATE_EMAIL),
                ...$options
            ]);
        }
    }
    

    Register it in PromptsServiceProvider:

    $this->app->singleton('prompts.email', fn() => new EmailPrompt());
    
  2. Override Default Prompts: Bind custom implementations in PromptsServiceProvider:

    $this->app->bind(\Moox\Prompts\Contracts\Prompt::class, CustomPrompt::class);
    
  3. Web Flow Customization: Override the web template in resources/views/vendor/moox-prompts/flow.blade.php:

    // Example: Add a progress bar.
    <progress max="{{ count($steps) }}" value="{{ $currentStep }}"></progress>
    
  4. CLI Styling: Use Symfony’s Output methods for custom styling:

    $this->text('Warning:', ['fg' => 'yellow']);
    
  5. Localization: Prompts support Laravel’s localization. Translate labels:

    $this->projectName = text(label: __('prompts.project_name'));
    

    Add translations to resources/lang/en/prompts.php:

    return [
        'project_name' => 'What is the project name?',
    ];
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle