https://github.com/ctf0/easy-searchable
search your model & relation with ease
https://github.com/ctf0/easy-searchable
laravel model php relational-databases search
Last synced: 2 months ago
JSON representation
search your model & relation with ease
- Host: GitHub
- URL: https://github.com/ctf0/easy-searchable
- Owner: ctf0
- License: mit
- Created: 2020-05-29T09:17:08.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2023-01-03T23:16:10.000Z (over 3 years ago)
- Last Synced: 2024-10-11T12:19:46.051Z (over 1 year ago)
- Topics: laravel, model, php, relational-databases, search
- Language: PHP
- Homepage:
- Size: 23.4 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
EasySearchable
## Installation
``` bash
composer require ctf0/easy-searchable
```
# Setup
> also check https://github.com/laravie/query-filter#search-queries
- in ur model add
```php
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
```php
// 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.
```php
// 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](mailto:ctf0-dev@protonmail.com).