-
composer.json
Open in GitHub{ // "require": { "php": "^7.4", "algolia/algoliasearch-client-php": "^3.0", // "laravel/scout": "^9.0" }, // }
-
app/Package.php
Open in GitHubuse Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; class Package extends Model { use Searchable; // public function toSearchableArray() { $packageAttributes = $this->toArray(); // Temporarily truncate to prevent algolia from throwing a size exceeded exception $packageAttributes['readme'] = substr($packageAttributes['readme'], 0, 500); $packageAttributes['instructions'] = substr($packageAttributes['instructions'], 0, 500); Arr::forget($packageAttributes, $this->excludeFromSearchIndex); // Add tags so we can filter them // @todo Make sure this is updated when tags are updated $packageAttributes['_tags'] = $this->tags->pluck('slug')->toArray(); return $packageAttributes; } // }
-
app/Http/Controllers/Api/SearchController.php
Open in GitHubuse App\CacheKeys; use App\Http\Controllers\Controller; use App\Http\Resources\Package as PackageResource; use App\Package; use Illuminate\Http\Request; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; class SearchController extends Controller { const CACHE_LENGTH = 10; public function __invoke(Request $request) { $this->validate($request, [ 'q' => 'required|min:3', ]); Log::info('API search for: '.$request->input('q')); return PackageResource::collection($this->searchFor($request->input('q'))); } private function searchFor($q) { return Cache::remember(CacheKeys::packageSearchResults($q), self::CACHE_LENGTH, function () use ($q) { return Package::search($q)->get()->load(['tags', 'author']); }); } }