ctf0/easy-searchable

search model & relation attributes with ease

Fund package maintenance!
ctf0

v1.1.6 2021-03-03 11:19 UTC

This package is auto-updated.

Last update: 2024-11-30 02:03:05 UTC


README

EasySearchable
Latest Stable Version Total Downloads

Installation

composer require ctf0/easy-searchable

Setup

also check https://github.com/laravie/query-filter#search-queries

  • in ur model add
use ctf0\EasySearchable\Traits\HasSearch;

class Post extends Model
{
    use HasSearch;

    // searched attributes
    //
    // when empty, all model fields will be searched
    // except "dates, primary_key, hidden"
    public $searchableAttributes = [];

    // or have a complete freedom and directly use
    public function getSearchableAttributes()
    {
        return [
            'name->' . app()->getLocale(),
            // ...
        ];
    }

    // ignore attributes
    //
    // so instead of listing all the needed columns in `$searchableAttributes`
    // you can ignore the ones you don't need here
    public $searchableAttributesIgnore = [];

    // searched relations
    //
    // when empty, no relation will be searched
    // * under each relation add the '$searchableAttributes' and we will pick them up automatically
    // * doesn't support nested relations
    public $searchableRelations  = [];

    // we search using the full sentence,
    // however if you prefer to search by words, then use
    public $replaceSpace = true;

    // to force searching dates
    public $searchableDates = true;
}

Usage

// auto search in model & relations attributes
Post::search('search for something')->get();

// to strict search even further, wrap the text with either `'` or `"`
Post::search('"search for something"')->get();

// search in specific fields
Post::search('search for something', ['columnName','relation.columnName'])->get();

Morph Relation Search

either use

// model
public function scopeWorkerSearch($query, $searchTerm)
{
    return $query->orWhereHasMorph(
        'workerable', // name of the morph relation
        '*',
        function ($q) use ($searchTerm) {
            $q->search($searchTerm);
        }
    );
}

// controller
return $query->search($text)->workerSearch($text);

Security

If you discover any security-related issues, please email ctf0-dev@protonmail.com.