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
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
rust
use chrono::{Duration, NaiveDate}; #[derive(Debug)] pub struct DateRange {
Parsing and iterating date ranges in Rust
error-handling
iterators
parsing
Intermediate
7 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.