technote/laravel-search-helper

Search helper for laravel


Keywords
search, laravel
License
GPL-2.0+

Documentation

Laravel Search Helper

Build Status Coverage Status CodeFactor License: MIT PHP: >=7.1.3

Search helper for Laravel.

Packagist

Install

composer require technote/laravel-search-helper

Usage

  1. Implement Searchable contract and Searchable Trait.
  2. Implement setConditions function.
    <?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 function.
    <?php
    use App\Models\Item;
    
    Item::search([
        's' => [
            'test',
        ],
        'ids' => [1, 2, 3],
    ])->get();

Author

GitHub (Technote)
Blog