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
- https://github.com/laravie/query-filter#search-with-morph-relations "which will disable the auto search the trait does"
- create a scope and chain it to ur search call ex.
// 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.