php
48 lines · 8 steps
A cached autocomplete endpoint in Laravel
A single-action controller validates a search term, ranks matching products, and caches the shaped results for five minutes.
Explained by
highlit
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\Product;
6use Illuminate\Http\JsonResponse;
7use Illuminate\Http\Request;
8use Illuminate\Support\Facades\Cache;
9use Illuminate\Support\Str;
10
11class AutocompleteController extends Controller
12{
13 public function __invoke(Request $request): JsonResponse
14 {
15 $validated = $request->validate([
16 'q' => ['required', 'string', 'min:2', 'max:50'],
17 'limit' => ['sometimes', 'integer', 'min:1', 'max:20'],
18 ]);
19
20 $term = Str::lower(trim($validated['q']));
21 $limit = $validated['limit'] ?? 8;
22 $cacheKey = "autocomplete:{$term}:{$limit}";
23
24 $results = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($term, $limit) {
25 return Product::query()
26 ->where('is_active', true)
27 ->where('name', 'like', "%{$term}%")
28 ->limit($limit * 4)
29 ->get(['id', 'name', 'slug'])
30 ->sortBy(function (Product $product) use ($term) {
31 $name = Str::lower($product->name);
32 $prefixRank = Str::startsWith($name, $term) ? 0 : 1;
33 $lengthRank = Str::length($name);
34
35 return [$prefixRank, $lengthRank, $name];
36 })
37 ->take($limit)
38 ->values()
39 ->map(fn (Product $product) => [
40 'id' => $product->id,
41 'label' => $product->name,
42 'url' => route('products.show', $product->slug),
43 ]);
44 });
45
46 return response()->json(['data' => $results]);
47 }
48}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Building the cache key from normalized inputs makes every distinct query safely cacheable and cache-hittable.
- 2Over-fetching then ranking in PHP lets you sort by relevance the database can't express cheaply.
- 3Shaping the response inside the cached closure means cached data is already client-ready, not raw models.
Related explainers
java
public record AppConfig( String host, int port, String databaseUrl,
Loading typed config from env vars in Java
records
configuration
environment-variables
Intermediate
6 steps
php
<?php namespace App\Validation;
Building a reusable address form validator in PHP
validation
error-accumulation
regex
Intermediate
9 steps
php
<?php declare(strict_types=1);
Normalizing human names in PHP
unicode
text-normalization
transliteration
Intermediate
8 steps
php
<?php namespace App\Http\Controllers;
Handling Stripe webhooks in Laravel
webhooks
signature-verification
dependency-injection
Intermediate
7 steps
go
package handler type flightResult struct { status int
Deduping in-flight requests in Gin
middleware
concurrency
deduplication
Advanced
9 steps
php
<?php namespace App\FeatureFlags;
How a feature flag evaluator decides
feature-flags
rollout
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-cached-autocomplete-endpoint-in-laravel-explained-php-e21a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.