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

Console Select Laravel Package

eddiriarte/console-select

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require eddiriarte/console-select
    
  2. Laravel/Laravel-Zero: Register the service provider in config/app.php:

    'providers' => [
        EddIriarte\Console\Providers\SelectServiceProvider::class,
    ],
    
  3. Symfony: Add the trait and helper to your command:

    use EddIriarte\Console\Traits\SelectableInputs;
    use EddIriarte\Console\Helpers\SelectionHelper;
    
    class MyCommand extends Command
    {
        use SelectableInputs;
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $this->getHelperSet()->set(
                new SelectionHelper($input, $output)
            );
        }
    }
    

First Use Case

Use select() in a command to prompt the user for input:

$selected = $this->select(
    'Choose a user role:',
    ['Admin', 'Editor', 'Viewer']
);

This will display an interactive selection menu with keyboard navigation.


Implementation Patterns

Common Workflows

  1. Single Selection (Radio Mode): Force single selection by passing false as the third argument:

    $role = $this->select('Pick a role:', ['Admin', 'Editor', 'Viewer'], false);
    
  2. Multi-Selection (Checkbox Mode): Default behavior allows multiple selections:

    $roles = $this->select('Pick all applicable roles:', ['Admin', 'Editor', 'Viewer']);
    
  3. Dynamic Options: Fetch options from a database or API before rendering:

    $users = User::all()->pluck('name')->toArray();
    $selected = $this->select('Select users:', $users);
    
  4. Conditional Logic: Use selected values to drive workflows:

    if (in_array('Admin', $selected)) {
        $this->info('Granting admin privileges...');
    }
    
  5. Integration with Laravel Artisan: Create custom Artisan commands for admin tasks:

    // app/Console/Commands/AssignRoles.php
    public function handle()
    {
        $roles = $this->select('Assign roles:', ['Admin', 'Editor'], false);
        // Logic to assign roles...
    }
    

Best Practices

  • Descriptive Prompts: Use clear, action-oriented questions (e.g., "Select users to notify:").
  • Default Values: Provide defaults where applicable (e.g., pre-selecting common roles).
  • Validation: Validate selections before processing:
    if (empty($selected)) {
        $this->error('No selections made.');
        return;
    }
    
  • Error Handling: Wrap calls in try-catch for graceful failures:
    try {
        $selected = $this->select('...');
    } catch (\Exception $e) {
        $this->error('Selection failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. No Multi-Line Support: Options with newlines (\n) may render poorly. Use short labels or truncate long text.

  2. Keyboard Navigation: Users expect arrow keys for navigation. Test with non-mouse users.

  3. Empty Selections: The package doesn’t enforce non-empty selections. Validate manually:

    if (empty($selected)) {
        throw new \RuntimeException('No option selected.');
    }
    
  4. Symfony Integration: Forgetting to add SelectionHelper to the helper set will throw errors. Always include:

    $this->getHelperSet()->set(new SelectionHelper($this->input, $this->output));
    
  5. Laravel Zero: Ensure the service provider is registered before using $this->select().

Debugging Tips

  • Check Output: Use $this->output->writeln() to debug option lists:
    $this->output->writeln(print_r($options, true));
    
  • Inspect Input: Log the raw $this->input object if selections behave unexpectedly.
  • Test Locally: Use php artisan [command] to test interactively.

Extension Points

  1. Custom Styling: Override the default renderer by extending EddIriarte\Console\Renderers\SelectionRenderer:

    class CustomRenderer extends SelectionRenderer
    {
        protected function renderOption($option, $selected)
        {
            // Custom logic here
        }
    }
    

    Register it via the service provider.

  2. Add Icons/Emojis: Prepend icons to options for visual cues:

    $options = [
        '👤 Admin',
        '✏️ Editor',
        '👁️ Viewer',
    ];
    
  3. Localization: Translate prompts/options using Laravel’s translation system:

    $prompt = __('Select a role');
    $options = __('Select roles') => ['Admin', 'Editor'];
    
  4. Async Data Loading: For large datasets, fetch options lazily (e.g., via AJAX in a custom renderer).

Configuration Quirks

  • No Built-in Config: The package relies on Symfony’s console component and doesn’t expose config options. Customize via:

    • Overriding traits/renderers.
    • Wrapping $this->select() in helper methods.
  • Legacy Support: Test on Laravel 5.6+ and Symfony 5.0+. Older versions may require polyfills.

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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui