Skip to content

Instantly share code, notes, and snippets.

@semihkeskindev
Created May 15, 2024 17:01
Show Gist options
  • Save semihkeskindev/9338b3fd4941bac162cb28bd64264f9c to your computer and use it in GitHub Desktop.
Save semihkeskindev/9338b3fd4941bac162cb28bd64264f9c to your computer and use it in GitHub Desktop.

Revisions

  1. semihkeskindev created this gist May 15, 2024.
    26 changes: 26 additions & 0 deletions search_builder_macro.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    Builder::macro('search', function ($attributes, $searchTerm, $compact = false): Builder {
    $this->where(function (Builder $query) use ($compact, $attributes, $searchTerm): void {
    if ($compact) {
    $joinedAttributes = '`'.implode('`, " " ,`', $attributes).'`';
    $query->orWhereRaw('upper('.\DB::raw("concat({$joinedAttributes})").') LIKE ?', ["%{$searchTerm}%"]);
    } else {
    foreach ($attributes as $attribute) {
    $query->when(
    str_contains($attribute, '.'),
    function (Builder $query) use ($attribute, $searchTerm): void {
    [$relationName, $relationAttribute] = explode('.', $attribute);

    $query->orHasByNonDependentSubquery($relationName, function (Builder $query) use ($relationAttribute, $searchTerm): void {
    $query->whereRaw('upper('.$relationAttribute.') LIKE ?', ["%{$searchTerm}%"]);
    });
    },
    function (Builder $query) use ($attribute, $searchTerm): void {
    $query->orWhereRaw('upper('.$attribute.') LIKE ?', ["%{$searchTerm}%"]);
    }
    );
    }
    }
    });

    return $this;
    });