-
app/Http/Controllers/SearchController.php
Open in GitHubuse App\Services\Search\SearchService; use Illuminate\Http\Request; use App\Models\Client; class SearchController extends Controller { public function search($query, $type) { if (config('services.elasticsearch.enabled')) { return response()->json(app(SearchService::class)->search($query, $type)); } $type = ucfirst(rtrim($type, 's')); $class = '\\App\\Models\\' . $type; $searchClass = new $class(); $result["hits"] = []; foreach ($searchClass->getSearchableFields() as $searchableField) { $classes = $searchClass->where($searchableField, 'LIKE', '%' . $query . '%')->get(); foreach ($classes as $class) { $source = new \stdClass(); $source->_source = new \stdClass(); if (!$class->displayValue() || !$class->searchLink()) { continue; } $source->_source->display_value = $class->displayValue(); $source->_source->link = $class->searchLink(); $result["hits"]["hits"][] = $source; } } return response()->json($result); } }
-
app/Services/Search/SearchService.php
Open in GitHubuse Elasticsearch\ClientBuilder; class SearchService { private $elasticsearch; public function getClient() { $host = config('elasticsearch.hosts'); if (is_null($this->elasticsearch)) { $builder = ClientBuilder::create()->setHosts($host); $this->elasticsearch = $builder->build(); } return $this->elasticsearch; } public function search($query, $type = 'clients', $prPage = 5, $offset = 0, $sortBy = null, $sortDirection = 'desc') { $elasticClient = $this->getClient(); $params = [ 'index' => $type, 'type' => $type, 'body' => [ 'size' => $prPage, 'from' => $offset, 'query' => [ 'multi_match' => [ 'fuzziness' => 'AUTO', 'query' => strtolower($query), ], ], ], ]; if (!is_null($sortBy)) { $params['body']['sort'] = [$sortBy => $sortDirection]; } $res = $elasticClient->search($params); return $res; } }
-
composer.json
Open in GitHub{ "require": { "php": ">=7.3.9", // "elasticsearch/elasticsearch": "^6.1" } }
-
config/services.php
Open in GitHubreturn [ // 'elasticsearch' => [ 'enabled' => env('ELASTICSEARCH_ENABLED', false), ], ];