Created
December 24, 2019 20:32
-
-
Save robbinbenard/69ecc1a8f046cd1d6aa1167639084397 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\Providers; | |
| use Illuminate\Support\Arr; | |
| use Illuminate\Support\Str; | |
| use Illuminate\Support\ServiceProvider; | |
| use Illuminate\Database\Eloquent\Builder; | |
| class QueryBuilderServiceProvider extends ServiceProvider | |
| { | |
| /** | |
| * Bootstrap services. | |
| * | |
| * @return void | |
| */ | |
| public function boot() | |
| { | |
| Builder::macro('search', function ($attributes) { | |
| $search = request()->query('search'); | |
| if (! $search) { | |
| return $this; | |
| } | |
| return $this->where(function (Builder $query) use ($attributes, $search) { | |
| foreach (Arr::wrap($attributes) as $attribute) { | |
| $query->when( | |
| Str::contains($attribute, '.'), | |
| function (Builder $query) use ($attribute, $search) { | |
| [$relation_name, $relation_attribute] = explode('.', $attribute); | |
| $query->orWhereHas($relation_name, function (Builder $query) use ($relation_attribute, $search) { | |
| $query->where($relation_attribute, 'LIKE', "%{$search}%"); | |
| }); | |
| }, | |
| function (Builder $query) use ($attribute, $search) { | |
| $query->orWhere($attribute, 'LIKE', "%{$search}%"); | |
| } | |
| ); | |
| } | |
| }); | |
| }); | |
| Builder::macro('filter', function ($allowed_filters) { | |
| $filters = request()->query('filter'); | |
| if (! is_array($filters) || ! count($filters)) { | |
| return $this; | |
| } | |
| $filters = array_filter(Arr::only($filters, $allowed_filters)); | |
| return $this->where(function (Builder $query) use ($filters) { | |
| foreach (Arr::wrap($filters) as $attribute => $value) { | |
| $query->when( | |
| Str::contains($attribute, '.'), | |
| function (Builder $query) use ($attribute, $value) { | |
| [$relation_name, $relation_attribute] = explode('.', $attribute); | |
| $query->orWhereHas($relation_name, function (Builder $query) use ($relation_attribute, $value) { | |
| $query->where($relation_attribute, $value); | |
| }); | |
| }, | |
| function (Builder $query) use ($attribute, $value) { | |
| $query->orWhere($attribute, $value); | |
| } | |
| ); | |
| } | |
| }); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment