Last active
December 18, 2019 12:46
-
-
Save spresnac/911d7834bdd6583b05c875ebd722e148 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use App\Model\BaseModel; | |
use Illuminate\Database\Eloquent\Builder; | |
use Illuminate\Database\Eloquent\Relations\Relation; | |
use Illuminate\Support\Collection; | |
use Illuminate\Support\Str; | |
/** | |
* Trait Searchable | |
* @package App\Traits | |
*/ | |
trait Searchable | |
{ | |
/** | |
* @param $result | |
* @param string $search | |
* @param BaseModel $model | |
* @return Collection|\Illuminate\Database\Eloquent\Collection | |
*/ | |
public function search($result, string $search, BaseModel $model) | |
{ | |
if ($result instanceof Collection) { | |
return $result->filter(static function ($row) use ($model, $search) { | |
foreach ($model->getFillable() as $field) { | |
if (mb_substr_count(Str::lower($row->{$field}), Str::lower($search)) > 0) { | |
return true; | |
} | |
} | |
return false; | |
}); | |
} | |
$result->select($model->getTable().'.*'); | |
return $result->where(static function (Builder $query) use ($model, $search, $result) { | |
foreach ($model->getFillable() as $field) { | |
$query->orWhere($model->getTable().'.'.$field, 'LIKE', '%'.$search.'%'); | |
} | |
foreach ($model->getRelations() as $relation) { | |
/** @var Relation $_relation */ | |
$_relation = $model->{$relation}(); | |
foreach ($_relation->getModel()->getFillable() as $fillable) { | |
$query->orWhere($_relation->getModel()->getTable() . '.' . $fillable, 'LIKE', '%'.$search.'%'); | |
} | |
$result->leftJoin( | |
$_relation->getModel()->getTable(), | |
$model->getTable().'.'.$_relation->getLocalKeyName(), | |
'=', | |
$_relation->getModel()->getTable().'.'.$_relation->getForeignKeyName() | |
); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment