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 Options Laravel Package

spatie/laravel-options

Generate unified select option lists in Laravel from enums, Eloquent models, states, and arrays. Spatie laravel-options converts sources to a consistent label/value structure, supports customization via config, and makes building dropdowns and filters faster and cleaner.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:
    • Unified Option Handling: Centralizes option generation logic (enums, models, arrays, etc.) into a single, reusable package, reducing boilerplate and improving maintainability.
    • Type Safety: Leverages PHP enums and model relationships, aligning with modern Laravel practices (e.g., enums introduced in PHP 8.1).
    • Extensibility: Supports custom option sources via the OptionSource interface, enabling domain-specific adaptations.
    • Lightweight: Minimal abstraction overhead; focuses solely on option transformation without introducing complex dependencies.
  • Fit for:
    • Forms/UX Layers: Ideal for dynamic dropdowns, filters, or form inputs where options are derived from multiple sources (e.g., database records, enums, or static arrays).
    • API Responses: Useful for standardizing option structures in API payloads (e.g., GET /options/users).
    • Admin Panels: Simplifies option management in back-office interfaces (e.g., Laravel Nova, Filament).
  • Misalignment:
    • Non-Option Use Cases: Not suitable for non-select UI components (e.g., checkbox groups without labels/values).
    • Performance-Critical Paths: Minimal runtime impact, but if options are generated on every request (e.g., in a loop), caching strategies may be needed.

Integration Feasibility

  • Laravel Compatibility:
    • Native Integration: Designed for Laravel (uses Illuminate\Support\Collection, Illuminate\Database\Eloquent\Model).
    • PHP Version: Requires PHP 8.1+ (for enums), aligning with Laravel 9+/10+.
    • Service Provider: Zero-configuration via auto-discovery (Laravel 5.5+).
  • Dependencies:
    • Minimal: Only requires Laravel core and PHP 8.1+.
    • No Conflicts: No known dependency clashes with popular Laravel packages (e.g., Spatie’s other packages, Laravel Breeze, Livewire).
  • Testing:
    • CI/CD Ready: Includes GitHub Actions for tests/PHPStan, ensuring reliability.
    • Unit Testable: Options can be mocked/stubbed for testing controllers or services.

Technical Risk

  • Low:
    • Proven Track Record: Spatie packages are battle-tested (252 stars, MIT license, active maintenance).
    • Backward Compatibility: Changelog indicates stable API evolution (e.g., no breaking changes in 1+ years).
    • Documentation: Clear README with examples and API reference.
  • Mitigable Risks:
    • Enum/Model Changes: If underlying enums/models change (e.g., renamed cases or columns), option labels/values must be updated. Mitigation: Use feature flags or database migrations for model changes.
    • Caching: Frequent option regeneration (e.g., per-request) could impact performance. Mitigation: Cache options at the service layer (e.g., Cache::remember).
    • Custom Sources: Extending for non-standard sources (e.g., API responses) requires understanding the OptionSource interface. Mitigation: Start with built-in sources; extend only if needed.

Key Questions

  1. Use Case Clarity:
    • Are options primarily used in UI forms, APIs, or both? This affects caching strategies and response formatting.
    • Example: For APIs, should options include metadata (e.g., is_default, priority)?
  2. Data Sources:
    • What percentage of options come from enums, models, or static arrays? This influences migration effort.
    • Example: If 80% are enums, integration is trivial; if 50% are dynamic queries, caching becomes critical.
  3. Performance:
    • How often are options regenerated? (e.g., per-request vs. pre-loaded).
    • Example: For admin panels, pre-load options at app startup; for user-specific filters, cache per-user.
  4. Extensibility Needs:
    • Will custom OptionSource implementations be required? If so, allocate time for testing/debugging.
  5. Testing Strategy:
    • Should option generation be tested in unit tests (mocking sources) or feature tests (simulating UI/API flows)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Native Support: Works seamlessly with Laravel’s:
      • Enums (PHP 8.1+).
      • Eloquent Models (for dynamic options).
      • Blade/Livewire/Inertia (for UI integration).
      • API Resources (for structured responses).
    • Complementary Packages:
      • Livewire/Alpine.js: Bind options dynamically to dropdowns.
      • Filament/Laravel Nova: Pre-configure option sources for admin panels.
      • Laravel Scout: Combine with searchable options (e.g., Options::forModel(User::class)->search('John')).
  • Non-Laravel PHP:
    • Limited: Package is Laravel-specific; requires Laravel’s service container and helpers.

Migration Path

  1. Assessment Phase:
    • Audit existing option sources (e.g., hardcoded arrays, manual queries).
    • Categorize by type (enum/model/array) and prioritize migration.
  2. Incremental Adoption:
    • Phase 1: Replace static arrays/enums with spatie/laravel-options.
      • Example: Convert ['status' => ['active', 'inactive']] to Options::forEnum(Status::class).
    • Phase 2: Migrate dynamic queries to model-based options.
      • Example: Replace User::pluck('name', 'id') with Options::forModel(User::class, 'name', 'id').
    • Phase 3: Extend for custom sources if needed (e.g., API responses).
  3. Tooling:
    • Use Laravel’s php artisan make:enum or model factories to generate sources.
    • Leverage IDE autocompletion (e.g., Options::forEnum( + enum class).

Compatibility

  • Backward Compatibility:
    • Zero Breaking Changes: Existing option arrays can coexist during migration.
    • Fallbacks: Use Options::forArray() for legacy arrays until fully migrated.
  • Version Alignment:
    • Test with Laravel 10.x (PHP 8.2+) and 9.x (PHP 8.1) if supporting older versions.
    • Monitor Spatie’s upgrade guide for future Laravel versions.

Sequencing

  1. Prerequisites:
    • Upgrade to PHP 8.1+ and Laravel 9+/10+ if not already.
    • Install via Composer:
      composer require spatie/laravel-options
      
  2. Core Integration:
    • Publish config (if needed) via php artisan vendor:publish --tag="laravel-options-config".
    • Register option sources in a service provider or config file (e.g., config/options.php).
  3. UI/API Integration:
    • Blade: Pass options to views:
      <select>
        @foreach (Options::forEnum(Hobbit::class) as $option)
          <option value="{{ $option['value'] }}">{{ $option['label'] }}</option>
        @endforeach
      </select>
      
    • Livewire: Bind to properties:
      public $hobbit;
      protected $options;
      public function mount() {
          $this->options = Options::forEnum(Hobbit::class)->toArray();
      }
      
    • API: Return in resources:
      public function toArray($request) {
          return [
              'options' => Options::forModel(User::class, 'name', 'id')->toArray(),
          ];
      }
      
  4. Testing:
    • Write unit tests for option sources (mock enums/models).
    • Test edge cases (e.g., empty results, custom labels).
  5. Deployment:
    • Roll out in stages (e.g., non-critical forms first).
    • Monitor performance (e.g., query logs for model-based options).

Operational Impact

Maintenance

  • Pros:
    • Reduced Boilerplate: Centralized logic minimizes future changes (e.g., updating a label requires one enum change).
    • Consistent Formatting: Enforces ['label', 'value'] structure across the app.
    • Easy Updates: Spatie’s package handles minor updates automatically (Composer).
  • Cons:
    • Dependency Management: Requires monitoring Spatie’s release cycle (though low-risk).
    • Custom Logic: Extending for niche cases (e.g., conditional options) may need maintenance.

Support

  • Troubleshooting:
    • Common Issues:
      • Missing Labels: Ensure enums/models have proper __toString() or getLabelAttribute().
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport