php 60 lines · 8 steps

Building a health check endpoint in Laravel

An invokable controller probes the database and cache, then reports a combined status with the right HTTP code.

Explained by highlit
1<?php
2 
3namespace App\Http\Controllers;
4 
5use Illuminate\Http\JsonResponse;
6use Illuminate\Support\Facades\Cache;
7use Illuminate\Support\Facades\DB;
8use Illuminate\Support\Str;
9use Throwable;
10 
11class HealthCheckController extends Controller
12{
13 public function __invoke(): JsonResponse
14 {
15 $checks = [
16 'database' => $this->checkDatabase(),
17 'cache' => $this->checkCache(),
18 ];
19 
20 $healthy = collect($checks)->every(fn (array $check) => $check['status'] === 'ok');
21 
22 return response()->json([
23 'status' => $healthy ? 'ok' : 'degraded',
24 'checks' => $checks,
25 'timestamp' => now()->toIso8601String(),
26 ], $healthy ? 200 : 503);
27 }
28 
29 private function checkDatabase(): array
30 {
31 try {
32 DB::connection()->getPdo();
33 DB::select('select 1');
34 
35 return ['status' => 'ok'];
36 } catch (Throwable $e) {
37 report($e);
38 
39 return ['status' => 'error', 'message' => $e->getMessage()];
40 }
41 }
42 
43 private function checkCache(): array
44 {
45 try {
46 $token = Str::uuid()->toString();
47 Cache::put('health:ping', $token, now()->addSeconds(5));
48 
49 if (Cache::get('health:ping') !== $token) {
50 return ['status' => 'error', 'message' => 'Cache read/write mismatch'];
51 }
52 
53 return ['status' => 'ok'];
54 } catch (Throwable $e) {
55 report($e);
56 
57 return ['status' => 'error', 'message' => $e->getMessage()];
58 }
59 }
60}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A health endpoint should actively exercise each dependency, not just report that the process is running.
  2. 2Returning 503 when a check fails lets load balancers and uptime monitors react without parsing the body.
  3. 3Wrapping each probe in try/catch isolates failures so one broken dependency still yields a structured report.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a health check endpoint in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code