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

Livewire Select Laravel Package

mitratek/livewire-select

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mitratek/livewire-select
    npm install --save-dev @alpinejs/collapse
    

    Ensure alpinejs and tailwindcss are already configured in your Laravel project.

  2. Publish Assets (if needed):

    npm run dev
    

    The package includes Tailwind/Alpine-based styling out-of-the-box.

  3. First Use Case: Create a Livewire component for a searchable dropdown (e.g., user role selection):

    // app/Http/Livewire/SelectRole.php
    use Livewire\Component;
    use Mitratek\LivewireSelect\LivewireSelect;
    
    class SelectRole extends Component
    {
        use LivewireSelect;
        public $role_id;
    
        public function render()
        {
            return view('livewire.select-role');
        }
    }
    
    <!-- resources/views/livewire/select-role.blade.php -->
    <livewire-select
        name="role_id"
        model="App\Models\Role"
        search="['name', 'description']"
        show="{name} ({id})"
        value="id"
        placeholder="Select a role..."
    />
    

Implementation Patterns

Core Workflows

  1. Dynamic Data Fetching:

    • Use search to define which model attributes trigger re-fetching:
      search="['name', 'email', 'slug']"  // Searches across these fields
      
    • For large datasets, implement pagination via the paginate option:
      <livewire-select
          name="user_id"
          model="App\Models\User"
          search="['name']"
          paginate="10"
      />
      
  2. Custom Display Logic:

    • Override the show attribute to format output:
      show="{name} (ID: {id})"  // Custom template for displayed items
      
    • Use Blade templates for complex rendering:
      <livewire-select
          name="product_id"
          model="App\Models\Product"
          show="<span class='font-bold'>{name}</span> - ${price}"
      />
      
  3. Integration with Forms:

    • Bind to existing form inputs:
      <form wire:submit="save">
          <livewire-select
              name="category_id"
              model="App\Models\Category"
              wire:model="category_id"
          />
          <button type="submit">Save</button>
      </form>
      
    • Validation: Leverage Livewire’s built-in validation:
      protected $rules = ['role_id' => 'required|exists:roles,id'];
      
  4. Async Operations:

    • Use debounce to optimize API calls:
      <livewire-select
          name="search_term"
          model="App\Models\SearchResult"
          search="['query']"
          debounce="500"  // 500ms delay
      />
      
  5. Nested Relationships:

    • Fetch related data via with:
      <livewire-select
          name="post_id"
          model="App\Models\Post"
          with="['author']"
          show="{title} by {author.name}"
      />
      

Gotchas and Tips

Common Pitfalls

  1. Model Requirements:

    • The package expects models to implement toSearchableArray() or use default search fields.
    • Fix: Extend your model or override the trait:
      class User extends Model
      {
          public function toSearchableArray()
          {
              return ['name', 'email', 'custom_field'];
          }
      }
      
  2. Alpine JS Conflicts:

    • If Alpine directives (e.g., x-data) interfere, wrap the component in a unique Alpine scope:
      <div x-data="{ open: false }">
          <livewire-select ... />
      </div>
      
  3. Tailwind Styling:

    • Customize via tailwind.config.js:
      module.exports = {
          theme: {
              extend: {
                  colors: {
                      'select-bg': '#f8fafc',
                      'select-border': '#e2e8f0',
                  }
              }
          }
      }
      
    • Override styles in your Blade file:
      <livewire-select
          name="status"
          class="select-custom"
          style="--select-bg: #e2e8f0;"
      />
      
  4. Performance with Large Datasets:

    • Lazy Loading: Use paginate and loadMore events:
      <livewire-select
          name="user_id"
          model="App\Models\User"
          paginate="20"
          @load-more="loadMoreUsers"
      />
      
    • Caching: Cache search results in your model:
      public function scopeSearch($query, $search)
      {
          return $query->where('name', 'like', "%{$search}%")
                        ->remember(60); // Cache for 60 mins
      }
      
  5. Debugging:

    • Log Search Queries: Add to your model:
      protected static function booted()
      {
          static::addGlobalScope('logSearch', function (Builder $builder) {
              if (app()->environment('local')) {
                  $builder->toSql(); // Log SQL in Laravel logs
              }
          });
      }
      
    • Check for JavaScript Errors: Open browser dev tools (F12) and inspect the wire:ignore element for Alpine/Livewire conflicts.

Pro Tips

  1. Reusable Components:

    • Create a base component for shared select logic:
      // app/Http/Livewire/BaseSelect.php
      use Mitratek\LivewireSelect\LivewireSelect;
      
      class BaseSelect extends Component
      {
          use LivewireSelect;
          public $selectedId;
          public $model;
          public $searchFields;
          public $displayFields;
      
          public function mount($model, $searchFields, $displayFields)
          {
              $this->model = $model;
              $this->searchFields = $searchFields;
              $this->displayFields = $displayFields;
          }
      
          public function render()
          {
              return view('livewire.base-select');
          }
      }
      
      <!-- resources/views/livewire/base-select.blade.php -->
      <livewire-select
          name="selectedId"
          model="{{ $model }}"
          search="{{ json_encode($searchFields) }}"
          show="{{ $displayFields }}"
      />
      
  2. Multi-Select:

    • Use multiple attribute (requires custom Alpine logic):
      <livewire-select
          name="tag_ids[]"
          model="App\Models\Tag"
          multiple
          search="['name']"
          show="{name}"
      />
      
    • Workaround: Extend the package or use a wrapper like livewire-select-multiple.
  3. Accessibility:

    • Add ARIA attributes for screen readers:
      <livewire-select
          name="accessibility_id"
          aria-label="Select an accessible option"
          aria-describedby="select-help"
      />
      
    • Ensure wire:model is properly labeled:
      <label for="role_id">User Role</label>
      <livewire-select
          name="role_id"
          id="role_id"
          ...
      />
      
  4. Testing:

    • Test search functionality with Livewire’s call():
      public function test_search_returns_results()
      {
          $component = new SelectRole();
          $component->search('admin'); // Trigger search
          $this->assertCount(1, $component->getSearchResults());
      }
      
    • Mock models for unit tests:
      $mockModel = Mockery::mock('App\Models\Role');
      $mockModel->shouldReceive('search')->andReturn([new Role(['name' => 'Test'])]);
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle