technote/laravel-search-helper

Search helper for laravel


README

CI Status codecov CodeFactor License: MIT PHP: >=7.4

Read this in other languages: English, 日本語.

Search helper for Laravel.

Packagist

Table of Contents

Details

Install

composer require technote/laravel-search-helper

Usage

  1. Implement Searchable Contract and Searchable Trait.

  2. Implement setConditions method.

    <?php
    namespace App\Models;
    
    use Eloquent;
    use Illuminate\Database\Eloquent\Builder;
    use Illuminate\Database\Eloquent\Model;
    use Technote\SearchHelper\Models\Contracts\Searchable as SearchableContract;
    use Technote\SearchHelper\Models\Traits\Searchable;
    
    /**
     * Class Item
     * @mixin Eloquent
     */
    class Item extends Model implements SearchableContract
    {
        use Searchable;
    
        /**
         * @var array
         */
        protected $guarded = [
            'id',
        ];
    
        /**
         * @param  Builder  $query
         * @param  array  $conditions
         */
        protected static function setConditions(Builder $query, array $conditions)
        {
            if (! empty($conditions['s'])) {
                collect($conditions['s'])->each(function ($search) use ($query) {
                    $query->where(function ($builder) use ($search) {
                        /** @var Builder $builder */
                        $builder->where('items.name', 'like', "%{$search}%");
                    });
                });
            }
        }
    }
  3. Call search method.

    <?php
    use App\Models\Item;
    
    Item::search([
        's' => [
            'test',
        ],
        'ids' => [1, 2, 3],
    ])->get();

Author

GitHub (Technote)
Blog