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

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-options
    

    No publisher or configuration required—just use the Options facade or helper.

  2. First Use Case: Convert an enum to select options in a Blade view:

    use Spatie\Options\Options;
    
    // In a controller or service
    $hobbitOptions = Options::forEnum(\App\Enums\Hobbit::class)->toArray();
    
    // Pass to Blade
    return view('hobbits.form', ['options' => $hobbitOptions]);
    
  3. Blade Integration:

    <select name="hobbit">
        @foreach ($options as $option)
            <option value="{{ $option['value'] }}">{{ $option['label'] }}</option>
        @endforeach
    </select>
    

Where to Look First

  • Facade: Spatie\Options\Options (or helper options()).
  • Core Methods:
    • forEnum() → Convert enums to options.
    • forModel() → Fetch model attributes as options.
    • forState() → Use Laravel’s state() helper for dynamic options.
    • forArray() → Manually define options.
  • Customization: Override labels/values via closures or callbacks.

Implementation Patterns

1. Enum-to-Options (Most Common)

// Convert enum to options with custom label/value
Options::forEnum(Hobbit::class)
    ->label(fn ($value) => ucfirst($value->value)) // Custom label logic
    ->value(fn ($value) => strtoupper($value->value)) // Custom value logic
    ->toArray();

2. Model-Based Options

Fetch active users for a dropdown:

Options::forModel(User::class)
    ->where('active', true)
    ->orderBy('name')
    ->label('name')
    ->value('id')
    ->toArray();

3. Dynamic State Options

Use Laravel’s state() helper for runtime options:

Options::forState('user.roles')
    ->label('name')
    ->value('id')
    ->toArray();

4. Array Options with Metadata

Options::forArray([
    ['id' => 1, 'name' => 'Admin', 'permissions' => ['create', 'delete']],
    ['id' => 2, 'name' => 'Editor', 'permissions' => ['edit']],
])
->label('name')
->value('id')
->withMeta('permissions') // Include extra data
->toArray();

5. Integration with Forms

Use with Laravel Collective or Livewire:

// Livewire component
public function mount() {
    $this->hobbitOptions = Options::forEnum(Hobbit::class)->toArray();
}

public function render() {
    return view('livewire.hobbit-selector', ['options' => $this->hobbitOptions]);
}

6. Caching Options

Cache options to avoid repeated queries:

// In a service or controller
$cachedOptions = Cache::remember('hobbit_options', now()->addHours(1), function () {
    return Options::forEnum(Hobbit::class)->toArray();
});

Gotchas and Tips

Pitfalls

  1. Enum Case Sensitivity:

    • Labels default to the enum case name. Override with a closure if needed:
      Options::forEnum(Hobbit::class)->label(fn ($value) => strtolower($value->name));
      
  2. Model Query Performance:

    • Always chain select() to avoid loading unnecessary columns:
      Options::forModel(User::class)
          ->select('id', 'name')
          ->where(...);
      
  3. State Helper Dependencies:

    • forState() relies on Laravel’s state() helper. Ensure the state is set before calling:
      state(['user.roles' => Role::all()]);
      
  4. Array Key Conflicts:

    • If using forArray(), ensure value keys are unique. Duplicate values may cause issues in select fields.

Debugging Tips

  • Inspect Raw Data: Use ->getOptions() to debug the intermediate option objects before conversion:

    $options = Options::forEnum(Hobbit::class)->getOptions();
    dd($options); // Inspect before toArray()
    
  • Custom Option Classes: Extend Spatie\Options\Option to add custom logic:

    class CustomOption extends \Spatie\Options\Option {
        public function getExtraData() {
            return ['custom_field' => $this->value->customField];
        }
    }
    
    Options::forModel(User::class)
        ->useOptionClass(CustomOption::class)
        ->toArray();
    

Extension Points

  1. Custom Sources: Add support for new data sources by extending the Options class or creating a new method:

    // Example: Add `forApiResponse()` method
    Options::macro('forApiResponse', function ($response) {
        return new OptionsCollection(array_map(fn ($item) => [
            'label' => $item['name'],
            'value' => $item['id'],
        ], $response->data));
    });
    
  2. Global Defaults: Set defaults in a service provider:

    Options::macro('forModel', function ($model) {
        return $this->forModel($model)
            ->select('id', 'name')
            ->where('active', true);
    });
    
  3. Localization: Override labels dynamically with translations:

    Options::forEnum(Hobbit::class)
        ->label(fn ($value) => __("hobbits.{$value->value}"));
    

Configuration Quirks

  • No Config File: The package is zero-config. All behavior is defined via method chaining.
  • Lazy Loading: Methods like toArray() trigger execution. Chain methods before calling toArray() for efficiency.
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