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

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer:

    composer require ringlesoft/laravel-selectable
    

    No additional configuration is required.

  2. First Use Case: Convert a Laravel collection to select options in a Blade template:

    <select name="user_id">
        {!! \App\Models\User::all()->toSelectOptions() !!}
    </select>
    

    This uses id as the value and name as the label by default.

  3. Quick Customization: Override defaults with inline parameters:

    <select name="user_id">
        {!! \App\Models\User::all()->toSelectOptions('email', 'uuid', '6490132934f22') !!}
    </select>
    

    Here, email is the label, uuid is the value, and '6490132934f22' is the selected option.

Where to Look First

  • README.md: Focus on the "Usage" section for basic and advanced examples.
  • Changelog: Check v1.0.4+ for IDE helper improvements and bug fixes.
  • Source Code: Explore Selectable class methods in src/Selectable.php for extension points.

Implementation Patterns

Core Workflows

  1. Basic Select Generation Use toSelectOptions() for simple dropdowns:

    {!! $users->toSelectOptions() !!}
    
    • Pro Tip: Cache the collection if querying frequently (e.g., User::query()->get()->toSelectOptions()).
  2. Fluent Builder Pattern Chain methods for complex selects:

    {!! $users
        ->toSelectable()
        ->withLabel(fn($user) => "{$user->first_name} {$user->last_name}")
        ->withSelected($currentUser->id)
        ->withDisabled(fn($user) => $user->is_inactive)
        ->toSelectOptions()
    !!}
    
    • Use Case: Multi-select forms, dynamic labels (e.g., concatenated fields), or conditional disabled states.
  3. API/SPA Integration Convert to an array for frontend consumption:

    $selectItems = User::all()->toSelectable()->toSelectItems();
    
    • Example Response:
      [
        { "label": "John Doe", "value": "1", "selected": true, "dataAttributes": { "hidden": false } }
      ]
      
    • Use Case: AJAX-driven selects (e.g., with Alpine.js or Vue).
  4. Grouped Options Leverage Laravel’s groupBy:

    {!! User::all()
        ->groupBy(fn($user) => $user->department)
        ->toSelectable()
        ->toSelectOptions()
    !!}
    
    • Output: Renders <optgroup> elements automatically.

Integration Tips

  • Form Requests: Use toSelectItems() to validate selected values:
    $request->validate(['user_ids' => 'required|array']);
    $selectedIds = $request->input('user_ids');
    
  • Dynamic Data Attributes: Add custom attributes for frontend logic:
    ->withDataAttribute('user-role', fn($user) => $user->role)
    
  • Non-Object Arrays: Handle flat/associative arrays:
    collect(['First', 'Second'])->toSelectOptions();
    collect([['name' => 'First', 'id' => 1]])->toSelectable()->withValue('id')->toSelectOptions();
    

Gotchas and Tips

Pitfalls

  1. Blade Template Queries

    • Issue: Avoid writing queries directly in Blade (e.g., User::all()->toSelectOptions()). Use a service layer or controller method instead.
    • Fix: Pass the collection from the controller:
      public function edit(User $user) {
          return view('edit', ['users' => User::all()]);
      }
      
  2. Closure Performance

    • Issue: Overusing closures in large collections (e.g., withLabel(fn($item) => ...)) can slow rendering.
    • Fix: Cache the collection or use simple field names where possible.
  3. Selected/Disabled Logic

    • Issue: Closures for withSelected/withDisabled are evaluated per item, which may not scale for complex logic.
    • Fix: Pre-filter the collection:
      $users->whereNotIn('id', [1, 2])->toSelectable()->withDisabled(fn($user) => $user->is_banned)
      
  4. IDE Autocompletion

    • Issue: Older Laravel versions may not recognize toSelectable() methods.
    • Fix: Install the IDE helper (included in v1.0.2+):
      composer require --dev ringlesoft/laravel-selectable-ide-helper
      

Debugging Tips

  • Inspect Select Items: Use toSelectItems() to debug the array structure before rendering:
    dd(User::all()->toSelectable()->toSelectItems());
    
  • Check for Duplicates: Ensure value fields are unique; duplicates may cause rendering issues.
  • Validate HTML Output: Use browser dev tools to verify attributes (e.g., data-*, class) are applied correctly.

Extension Points

  1. Custom Selectable Builder Extend the Selectable class to add domain-specific methods:

    class CustomSelectable extends \Ringlesoft\Selectable\Selectable {
        public function withCustomAttribute(string $name, $value) {
            return $this->withDataAttribute($name, $value);
        }
    }
    
    • Use Case: Domain-specific attributes (e.g., withPriority()).
  2. Override Defaults Globally Use a macro to modify default behavior:

    \Ringlesoft\Selectable\Selectable::macro('withDefaultClasses', function() {
        return $this->withClass('select-option');
    });
    
    • Use Case: Enforce consistent styling across all selects.
  3. Non-Laravel Collections Support arrays or custom objects by implementing Arrayable:

    collect([1, 2, 3])->toSelectable()->withValue(fn($item) => "item_$item");
    

Configuration Quirks

  • No Config File: The package is zero-config, but ensure your Laravel version (≥8.x) supports the syntax.
  • Multiple Selects: For <select multiple>, ensure your frontend handles array submissions (e.g., user_ids[]).
  • Empty Collections: toSelectOptions() renders an empty <select>; add a placeholder if needed:
    <select name="user_id">
        <option value="" disabled selected>Select a user</option>
        {!! $users->toSelectOptions() !!}
    </select>
    
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