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

Laravel Selectable Laravel Package

ringlesoft/laravel-selectable

Generate HTML tags from Laravel collections with a simple, flexible API. Choose label/value fields (strings or closures), set selected/disabled items, add classes/data attributes, group options, and export selectable arrays for AJAX/SPAs.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Laravel-Native: Seamlessly integrates with Laravel’s Eloquent collections, leveraging existing query-building patterns (e.g., groupBy, where). Aligns with Laravel’s philosophy of fluent, chainable methods.
    • Separation of Concerns: Decouples HTML generation logic from business logic, adhering to MVC principles. The Selectable object acts as a middleware layer between collections and UI.
    • Extensibility: Supports closures for dynamic label/value generation, enabling custom logic without modifying core package code. Compatible with Laravel’s service container for dependency injection.
    • SPA/API-Friendly: toSelectItems() outputs structured arrays, ideal for frontend frameworks (React/Vue) or GraphQL responses.
  • Cons:

    • Blade-Centric: Primary use case assumes Blade templating. While toSelectItems() addresses SPAs, the package lacks native support for non-Blade environments (e.g., Livewire, Inertia.js).
    • Limited Validation: No built-in validation for selected/disabled values (e.g., ensuring they match collection keys). Risk of runtime errors if misconfigured.
    • Monolithic Methods: Chaining methods like withLabel()->withValue() can become verbose for complex selects. No support for partial updates (e.g., modifying only labels post-initialization).

Integration Feasibility

  • Laravel Ecosystem Compatibility:

    • Eloquent Models: Works out-of-the-box with Model::query()->get()->toSelectOptions().
    • API Resources: Can be integrated into JsonResource via toSelectItems() for consistent API responses.
    • Form Requests: Compatible with Laravel’s FormRequest validation (e.g., validating selected values against the package’s output).
    • Testing: Supports Pest/PHPUnit via collect([])->toSelectable()->toSelectOptions() for unit tests.
  • Non-Laravel PHP:

    • Partial Support: Requires Laravel’s Collection class. For vanilla PHP, wrap arrays in collect() (e.g., collect($array)->toSelectOptions()).
    • Dependencies: Only requires Laravel 8+ (no framework bloat). Lightweight (~1MB installed size).

Technical Risk

Risk Area Severity Mitigation
Breaking Changes Low MIT license + changelog. Backward-compatible since v1.0.0 (2023).
Performance Medium Optimized rendering in v1.0.4. Test with large collections (>10K items).
Security Low No XSS risks (outputs escaped HTML). Input validation depends on upstream data.
IDE Tooling Medium IDE helper (v1.0.2+) improves autocompletion, but may require manual setup.
Concurrency Low Stateless; no shared resources. Safe for multi-threaded environments.

Key Questions for TPM

  1. Use Case Alignment:
    • Are we generating selects primarily in Blade, SPAs, or APIs? (Affects whether toSelectOptions() or toSelectItems() is prioritized.)
    • Do we need grouped selects (e.g., <optgroup>)? The package supports groupBy() but lacks native HTML <optgroup> generation.
  2. Customization Needs:
    • Will we need dynamic attributes (e.g., data-*) beyond what withDataAttribute() offers? (Example: Conditional ARIA labels.)
    • Is multi-language support required? (Package doesn’t natively handle translations.)
  3. Team Skills:
    • Is the team comfortable with closure-based configurations (e.g., fn($item) => ...)? Steeper learning curve than string-based methods.
    • Do we have PHP/Laravel experts to handle edge cases (e.g., custom value mappings)?
  4. Alternatives:
    • Compare with:
      • Livewire Select: For real-time selects (e.g., search-as-you-type).
      • Filament Forms: If using Filament for admin panels.
      • Custom Blade Components: For highly customized UIs.
  5. Long-Term Maintenance:
    • Is the author active? (Last release: 2025-04-22; 5 stars but 0 dependents suggest niche use.)
    • Do we need enterprise support? (MIT license = community-driven.)

Integration Approach

Stack Fit

Component Compatibility Notes
Laravel Core ✅ Full support (Collections, Eloquent, Blade) Zero-config installation.
Frontend ⚠️ Partial Blade: Native. SPAs: Use toSelectItems() + frontend library (e.g., select2).
APIs ✅ Full toSelectItems() returns structured arrays for GraphQL/REST.
Testing ✅ Full Works with Pest/PHPUnit. Mock Selectable for isolated tests.
CI/CD ✅ Full No build steps required. Composer dependency.
Monitoring ❌ None No telemetry or error tracking. Log custom metrics if using toSelectOptions() in production.

Migration Path

  1. Pilot Phase (1–2 Sprints):

    • Scope: Replace 1–2 simple selects in a non-critical feature (e.g., user role dropdown).
    • Steps:
      1. Install: composer require ringlesoft/laravel-selectable.
      2. Replace manual <option> loops with Model::query()->toSelectOptions().
      3. Test edge cases (e.g., empty collections, non-string values).
    • Success Metrics: 20% reduction in template code, no runtime errors.
  2. Rollout Phase:

    • Target: All Blade-based selects in the codebase.
    • Prioritization:
      • High: Admin panels (e.g., user management).
      • Medium: Public-facing forms (e.g., checkout).
      • Low: Legacy selects with hardcoded options.
    • Tooling:
      • Add IDE helper to composer.json for autocompletion:
        "extra": {
          "ide-helper": "vendor/ringlesoft/laravel-selectable/src/Selectable.php"
        }
        
      • Run composer dump-autoload post-install.
  3. Advanced Phase (Optional):

    • Custom Extensions:
      • Create a trait to extend Selectable (e.g., withTranslatedLabels() for i18n).
      • Example:
        trait TranslatableSelectable {
            public function withTranslatedLabels(string $locale): self {
                return $this->withLabel(fn($item) => __($item->name, [], $locale));
            }
        }
        
    • API Integration:
      • Use toSelectItems() in JsonResource:
        public function toArray($request) {
            return [
                'selectOptions' => User::all()->toSelectable()->toSelectItems(),
            ];
        }
        

Compatibility

Scenario Compatibility Workaround
Non-Object Arrays ✅ (v1.0.3+) collect($array)->toSelectOptions().
Multiple Selects Add multiple to <select> tag.
Dynamic Data Attributes Use withDataAttribute('key', fn($item) => $item->dynamic_value).
Grouped Options ⚠️ Partial Use groupBy() + manual <optgroup> in Blade.
Livewire/Alpine.js Use toSelectItems() + frontend library (e.g., Alpine’s @bind with wire:model).
Database Changes No schema changes required.

Sequencing

  1. Prerequisites:
    • Laravel 8+ (PHP 8.0+).
    • Blade templates or API endpoints using collect().
  2. Order of Adoption:
    • Step 1: Basic selects (e.g., User::all()->toSelectOptions()).
    • Step 2: Customized selects (e.g., withLabel()->withSelected()).
    • Step 3: Advanced features (e.g., toSelectItems() for APIs, withDataAttribute()).
    • Step 4: Extensions (e.g., traits for translations, caching).
  3. **Dependencies
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor