Skip to content

Commit

Permalink
fix searching
Browse files Browse the repository at this point in the history
  • Loading branch information
uyab committed Nov 14, 2019
1 parent 183fc4b commit e7ca0b2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

namespace Laravolt\Indonesia;

use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Foundation\Application;
use Illuminate\Support\Arr;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use Illuminate\Support\Str;
use Laravolt\Indonesia\Commands\SeedCommand;
use Laravolt\Indonesia\Commands\SyncCoordinateCommand;

Expand Down Expand Up @@ -57,6 +60,8 @@ public function boot()
if ($this->app->bound('laravolt.acl')) {
$this->app['laravolt.acl']->registerPermission(Permission::toArray());
}

$this->registerMacro();
}

protected function registerMenu()
Expand All @@ -82,6 +87,35 @@ protected function registerMenu()
}
}

protected function registerMacro()
{
if (!EloquentBuilder::hasGlobalMacro('whereLike')) {
EloquentBuilder::macro('whereLike', function ($attributes, string $searchTerm) {
$this->where(function (EloquentBuilder $query) use ($attributes, $searchTerm) {
foreach (Arr::wrap($attributes) as $attribute) {
$query->when(
Str::contains($attribute, '.'),
function (EloquentBuilder $query) use ($attribute, $searchTerm) {
[$relationName, $relationAttribute] = explode('.', $attribute);

$query->orWhereHas($relationName,
function (EloquentBuilder $query) use ($relationAttribute, $searchTerm) {
$query->where($relationAttribute, 'LIKE', "%{$searchTerm}%");
});
},
function (EloquentBuilder $query) use ($attribute, $searchTerm) {
$table = $query->getModel()->getTable();
$query->orWhere(sprintf('%s.%s', $table, $attribute), 'LIKE', "%{$searchTerm}%");
}
);
}
});

return $this;
});
}
}

protected function registerRoutes()
{
$router = $this->app['router'];
Expand Down
8 changes: 8 additions & 0 deletions tests/IndonesiaTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public function it_can_call_indonesia_service()
$this->checkCities();
$this->checkDistricts();
$this->checkVillages();
$this->search();
}

public function checkProvinces()
Expand Down Expand Up @@ -173,4 +174,11 @@ public function checkVillages()
$this->assertNotEmpty($result->district->city);
$this->assertNotEmpty($result->district->city->province);
}

public function search()
{
$results = \Indonesia::search('BATAM')->all();

$this->assertNotEmpty($results);
}
}

0 comments on commit e7ca0b2

Please sign in to comment.