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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Building the cache key from normalized inputs makes every distinct query safely cacheable and cache-hittable.
  2. 2Over-fetching then ranking in PHP lets you sort by relevance the database can't express cheaply.
  3. 3Shaping the response inside the cached closure means cached data is already client-ready, not raw models.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A cached autocomplete endpoint in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code