LARAVEL

Laravel Health Check Endpoints

May 15, 2024 10 min read

Introduction

Health check endpoints are essential for monitoring application status, especially in containerized and microservices architectures. Laravel makes it easy to implement comprehensive health checks.

Basic Endpoint

// routes/api.php
use Illuminate\Support\Facades\Cache;

Route::get('/health', function () {
    return response()->json([
        'status' => 'healthy',
        'timestamp' => now()->toIso8601String(),
        'version' => '1.0.0'
    ]);
});

Health Checks

Route::get('/health', function () {
    $checks = [
        'database' => $this->checkDatabase(),
        'cache' => $this->checkCache(),
        'queue' => $this->checkQueue(),
    ];
    
    $healthy = !in_array(false, $checks);
    
    return response()->json([
        'status' => $healthy ? 'healthy' : 'unhealthy',
        'checks' => $checks
    ], $healthy ? 200 : 503);
});

Database Checks

function checkDatabase() {
    try {
        DB::connection()->getPdo();
        return true;
    } catch (Exception $e) {
        return false;
    }
}

Cache Checks

function checkCache() {
    try {
        Cache::put('health_check', true, 10);
        return Cache::get('health_check') === true;
    } catch (Exception $e) {
        return false;
    }
}

Custom Checks

function checkExternalAPI() {
    try {
        $response = Http::timeout(5)->get('https://api.example.com/health');
        return $response->successful();
    } catch (Exception $e) {
        return false;
    }
}

function checkDiskSpace() {
    $free = disk_free_space('/');
    $total = disk_total_space('/');
    $percentage = ($free / $total) * 100;
    
    return $percentage > 10;
}

Summary

Implementing health check endpoints in Laravel is essential for monitoring application health in production. By checking database connectivity, cache functionality, and external services, you can ensure your application is running properly.

For more information, check out our other tutorials on Laravel Pulse and Laravel Octane.