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

Model Search Kit Laravel Package

beid212/model-search-kit

Laravel-пакет для выноса логики поиска: фильтрации и сортировки моделей в отдельные классы. Упрощает поддержку запросов и повторное использование фильтров. Установка через Composer, публикация конфигов через vendor:publish.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require beid212/model-search-kit
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Beid212\ModelSearchKit\ServiceProvider"
    
  2. Basic Usage Define a searchable model (e.g., User):

    use Beid212\ModelSearchKit\Searchable;
    
    class User extends Model implements Searchable
    {
        use \Beid212\ModelSearchKit\Traits\SearchableTrait;
    }
    
  3. First Query

    $search = new \Beid212\ModelSearchKit\Search(User::class);
    $search->filter('name', 'John'); // Exact match
    $search->filter('age', '>', 25); // Range filter
    $results = $search->execute();
    
  4. Key Config Check config/model-search-kit.php for default filter operators (e.g., =, >, <, contains).


Implementation Patterns

1. Filtering Workflows

  • Basic Filters

    $search->filter('status', 'active'); // Equality
    $search->filter('created_at', '<', now()->subYear()); // Date range
    
  • Dynamic Filtering (Request-Based)

    public function index(Request $request)
    {
        $search = new \Beid212\ModelSearchKit\Search(User::class);
        $search->applyRequestFilters($request); // Auto-parses `?name=John&status=active`
        return $search->execute();
    }
    
  • Custom Operators Extend the FilterOperator enum or override in config:

    'operators' => [
        'contains' => 'LIKE',
        'starts_with' => 'LIKE',
        'ends_with' => 'LIKE',
    ],
    

2. Sorting

  • Default Sort

    $search->sort('name', 'asc'); // or 'desc'
    
  • Multi-Field Sort

    $search->sort(['name' => 'asc', 'created_at' => 'desc']);
    

3. Integration with Eloquent

  • Paginated Results

    $results = $search->paginate(10); // Returns \Illuminate\Pagination\LengthAwarePaginator
    
  • Eager Loading

    $search->with(['posts', 'profile']); // Uses Eloquent's `with()`
    

4. API Resource Integration

  • Serialize Filters/Sorts
    $meta = [
        'filters' => $search->getFilters(),
        'sort' => $search->getSort(),
    ];
    return response()->json($results, 200, $meta);
    

Gotchas and Tips

Pitfalls

  1. SQL Injection Risk

    • Fix: The package escapes inputs by default, but validate request data (e.g., age must be numeric) to avoid edge cases.
  2. Case Sensitivity

    • Issue: filter('name', 'john') may not match John in MySQL.
    • Fix: Use LOWER() in custom operators or normalize case in config:
      'operators' => [
          'icontains' => 'LIKE LOWER(:value)',
      ],
      
  3. Performance with Complex Filters

    • Tip: Add database indexes for frequently filtered columns (e.g., status, created_at).
    • Debug: Use ->toSql() on the query builder to inspect generated SQL.
  4. Nested Relationship Filters

    • Limitation: Direct filtering on nested attributes (e.g., user.posts.title) isn’t supported out-of-the-box.
    • Workaround: Use raw queries or join tables manually.

Debugging Tips

  • Log Queries

    \DB::enableQueryLog();
    $search->execute();
    \Log::info(\DB::getQueryLog());
    
  • Validate Config Ensure config/model-search-kit.php matches your database dialect (e.g., LIKE vs. ILIKE for PostgreSQL).

Extension Points

  1. Custom Filter Classes Override Beid212\ModelSearchKit\Filters\Filter to add logic (e.g., multi-value filters):

    class MultiValueFilter extends Filter
    {
        public function apply(Builder $query, $value)
        {
            $values = explode(',', $value);
            return $query->whereIn('column', $values);
        }
    }
    
  2. Hooks for Pre/Post-Execution Use events (if the package supports them) or wrap the Search class:

    $search = new CustomSearch($model);
    $search->onExecute(function ($query) {
        $query->where('active', true);
    });
    
  3. Testing Mock the Search class or use Laravel’s query builder assertions:

    $search = new \Beid212\ModelSearchKit\Search(User::class);
    $search->filter('name', 'John');
    $query = $search->getQuery();
    $query->toSql(); // Assert SQL matches expectations
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui