laravel globale search
<?php
namespace App\Search;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
class GlobalSearch
{
public static function search(Builder $builder, Request $request): Builder
{
$searchableFields = $builder->getModel()->getFillable();
$relations = $builder->getModel()->getRelationsInModel();
return $builder->where(function ($query) use ($searchableFields, $request) {
//search in model with any word
if ($request->filled('search')) {
foreach ($searchableFields as $key => $value) {
$query->Where($value, $request->search);
}
}
//search with relations
foreach ($relations as $relationName => $relatedModel) {
$searchableFieldsRelated = $relatedModel->getFillable();
foreach ($request->all() as $key => $value) {
if (in_array($key, $searchableFields) && !is_null($value)) {
$query->orWhereHas($relationName, function ($query2) use ($key, $value) {
$query2->where($key, $value);
});
}
}
}
});
}
}