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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A health endpoint should actively exercise each dependency, not just report that the process is running.
- 2Returning 503 when a check fails lets load balancers and uptime monitors react without parsing the body.
- 3Wrapping each probe in try/catch isolates failures so one broken dependency still yields a structured report.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
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/building-a-health-check-endpoint-in-laravel-explained-php-0e31/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.