PHPackages                             philiprehberger/laravel-healthcheck - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. philiprehberger/laravel-healthcheck

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

philiprehberger/laravel-healthcheck
===================================

Configurable health check endpoint with built-in checks and Kubernetes probe support

v1.2.1(3mo ago)142MITPHPPHP ^8.2CI passing

Since Mar 9Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/laravel-healthcheck)[ Packagist](https://packagist.org/packages/philiprehberger/laravel-healthcheck)[ Docs](https://github.com/philiprehberger/laravel-healthcheck)[ RSS](/packages/philiprehberger-laravel-healthcheck/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (19)Versions (10)Used By (0)

Laravel Healthcheck
===================

[](#laravel-healthcheck)

[![Tests](https://github.com/philiprehberger/laravel-healthcheck/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/laravel-healthcheck/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/0f49c1a3f4bd09f7800a3f91305c8c5e38f77c5738b6dee620575d24b4de25ba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f6c61726176656c2d6865616c7468636865636b2e737667)](https://packagist.org/packages/philiprehberger/laravel-healthcheck)[![Last updated](https://camo.githubusercontent.com/9ce408cc4685db5d3c723c9fed9a8fbff0f73bb7788ff98112c87471835bd232/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f6c61726176656c2d6865616c7468636865636b)](https://github.com/philiprehberger/laravel-healthcheck/commits/main)

Configurable health check endpoint with built-in checks and Kubernetes probe support.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11 or 12

Installation
------------

[](#installation)

```
composer require philiprehberger/laravel-healthcheck
```

Laravel's package auto-discovery registers the service provider automatically.

### Publishing the config

[](#publishing-the-config)

```
php artisan vendor:publish --tag=healthcheck-config
```

This creates `config/healthcheck.php`.

Usage
-----

[](#usage)

### Basic health check

[](#basic-health-check)

Once installed, the following endpoints are immediately available:

EndpointDescription`GET /health`Full report — `200` if healthy, `503` if not`GET /health/live`Liveness probe — always `200``GET /health/ready`Readiness probe — `200` if healthy, `503` if notExample response from `GET /health`:

```
{
  "status": "ok",
  "duration_ms": 14.52,
  "checks": [
    {
      "name": "database",
      "status": "ok",
      "message": "Database connection is healthy.",
      "meta": { "connection": "mysql" }
    },
    {
      "name": "cache",
      "status": "ok",
      "message": "Cache is healthy.",
      "meta": []
    },
    {
      "name": "environment",
      "status": "ok",
      "message": "Environment configuration looks healthy.",
      "meta": { "env": "production", "debug": false }
    }
  ]
}
```

When any check is **critical** or **warning**, the overall `status` reflects that and the HTTP status code becomes `503`.

### Status levels

[](#status-levels)

LevelMeaning`ok`Check passed`degraded`Partial failure or performance issue`warning`Non-fatal issue (e.g. debug enabled)`critical`Check failed — affects readinessThe overall report status uses the `HealthStatus` enum and resolves as: `critical` if any check is critical; `degraded` if any is degraded or warning (but none critical); `ok` only if all checks pass.

### Configuration

[](#configuration)

`config/healthcheck.php`:

```
return [
    'route_prefix' => env('HEALTHCHECK_ROUTE_PREFIX', 'health'),

    'middleware' => [],

    'checks' => [
        \PhilipRehberger\Healthcheck\Checks\DatabaseCheck::class,
        \PhilipRehberger\Healthcheck\Checks\CacheCheck::class,
        \PhilipRehberger\Healthcheck\Checks\StorageCheck::class,
        \PhilipRehberger\Healthcheck\Checks\EnvironmentCheck::class,
    ],

    'timeout' => (int) env('HEALTHCHECK_TIMEOUT', 5),

    'cache' => [
        'enabled' => (bool) env('HEALTHCHECK_CACHE_ENABLED', false),
        'ttl'     => (int) env('HEALTHCHECK_CACHE_TTL', 30),
    ],
];
```

#### Restricting access with middleware

[](#restricting-access-with-middleware)

```
'middleware' => ['auth:sanctum'],
```

Or use a custom IP-allowlist middleware for infrastructure-only access.

#### Enabling result caching

[](#enabling-result-caching)

To avoid hammering your database on every probe poll:

```
HEALTHCHECK_CACHE_ENABLED=true
HEALTHCHECK_CACHE_TTL=30
```

### Built-in checks

[](#built-in-checks)

#### DatabaseCheck

[](#databasecheck)

Tests that a PDO connection can be established.

```
new DatabaseCheck()                    // uses default connection
new DatabaseCheck('mysql_reporting')   // named connection
```

#### CacheCheck

[](#cachecheck)

Writes, reads, and deletes a probe key using the default cache driver. Resource cleanup is guaranteed — the probe key is always removed via `try-finally`, even if cache operations fail.

#### StorageCheck

[](#storagecheck)

Writes, reads, and deletes a probe file on the default filesystem disk. Resource cleanup is guaranteed — the probe file is always deleted via `try-finally`, even if read or content verification fails.

```
new StorageCheck()        // default disk
new StorageCheck('s3')    // named disk
```

#### RedisCheck

[](#redischeck)

Calls `PING` on the Redis connection. Returns a warning (not critical) if the Redis extension and Predis are both absent so the check degrades gracefully in environments without Redis.

```
new RedisCheck()             // default connection
new RedisCheck('cache')      // named connection
```

#### QueueCheck

[](#queuecheck)

Resolves the queue connection from the container to verify connectivity.

```
new QueueCheck()             // default connection
new QueueCheck('redis')      // named connection
```

#### EnvironmentCheck

[](#environmentcheck)

Returns a **warning** when `APP_DEBUG=true` in a production environment.

#### HttpCheck

[](#httpcheck)

Pings an external URL and verifies the response status code.

```
new HttpCheck('https://api.stripe.com')
new HttpCheck('https://api.stripe.com', timeout: 3, expectedStatus: 200, checkName: 'stripe')
```

Register via the service container for constructor-injected checks:

```
// AppServiceProvider::register()
$this->app->bind(\PhilipRehberger\Healthcheck\Checks\HttpCheck::class, fn () =>
    new \PhilipRehberger\Healthcheck\Checks\HttpCheck(
        url: 'https://api.stripe.com',
        checkName: 'stripe_api',
    )
);
```

Then add the class string to `config/healthcheck.php` `checks` array.

### Writing custom checks

[](#writing-custom-checks)

Implement the `HealthCheck` contract:

```
use PhilipRehberger\Healthcheck\CheckResult;
use PhilipRehberger\Healthcheck\Contracts\HealthCheck;

class ElasticsearchCheck implements HealthCheck
{
    public function name(): string
    {
        return 'elasticsearch';
    }

    public function check(): CheckResult
    {
        try {
            $info = app('elasticsearch')->info();

            return CheckResult::ok(
                $this->name(),
                'Elasticsearch is healthy.',
                ['version' => $info['version']['number']],
            );
        } catch (\Throwable $e) {
            return CheckResult::critical($this->name(), $e->getMessage());
        }
    }
}
```

Register in `config/healthcheck.php`:

```
'checks' => [
    // ...
    ElasticsearchCheck::class,
],
```

### Degraded status

[](#degraded-status)

Use the `degraded` factory when a check is partially failing or experiencing performance issues:

```
public function check(): CheckResult
{
    $latency = $this->measureLatency();

    if ($latency > 1000) {
        return CheckResult::degraded(
            $this->name(),
            'High latency detected.',
            ['latency_ms' => $latency],
        );
    }

    return CheckResult::ok($this->name(), 'Healthy.', ['latency_ms' => $latency]);
}
```

### Attaching metrics

[](#attaching-metrics)

Attach arbitrary metrics to any check result using `withMetrics()`. Metrics are aggregated on the report via `getMetrics()`:

```
$result = CheckResult::ok('database', 'Healthy.')
    ->withMetrics([
        'latency_ms' => 5,
        'connections' => 10,
        'pool_usage' => 0.42,
    ]);

// In the report:
$report = $healthService->runAll();
$metrics = $report->getMetrics();
// ['database' => ['latency_ms' => 5, 'connections' => 10, 'pool_usage' => 0.42]]
```

### Kubernetes probe configuration

[](#kubernetes-probe-configuration)

#### Deployment manifest

[](#deployment-manifest)

```
livenessProbe:
  httpGet:
    path: /health/live
    port: 8080
  initialDelaySeconds: 10
  periodSeconds: 15
  failureThreshold: 3

readinessProbe:
  httpGet:
    path: /health/ready
    port: 8080
  initialDelaySeconds: 5
  periodSeconds: 10
  failureThreshold: 2
```

**Liveness** (`/health/live`) — always returns `200` as long as PHP-FPM/Octane is alive. Kubernetes will restart the container only if this stops responding, not on application-level failures.

**Readiness** (`/health/ready`) — returns `200` only when all health checks pass. Kubernetes removes the pod from load balancer rotation while this returns `503`, enabling zero-downtime deploys during database migrations or cold-start delays.

#### Ingress — skip auth middleware on probe endpoints

[](#ingress--skip-auth-middleware-on-probe-endpoints)

If you add auth middleware globally, exclude the probe paths in your ingress or use a separate middleware group:

```
// config/healthcheck.php
'route_prefix' => 'health',
'middleware'   => [],   // no auth on probes — protect at the network level instead
```

API
---

[](#api)

### `HealthCheck` (Interface)

[](#healthcheck-interface)

MethodReturn TypeDescription`name(): string``string`Unique check identifier`check(): CheckResult``CheckResult`Execute the check and return a result### `HealthStatus` (Enum)

[](#healthstatus-enum)

CaseValueDescription`HealthStatus::Ok``'ok'`All checks passed`HealthStatus::Degraded``'degraded'`Partial failure or performance issue`HealthStatus::Critical``'critical'`One or more checks failed### `CheckResult`

[](#checkresult)

MethodDescription`CheckResult::ok(string $name, string $message, array $meta)`Passing result`CheckResult::degraded(string $name, string $message, array $meta)`Degraded/partial failure`CheckResult::warning(string $name, string $message, array $meta)`Non-fatal warning`CheckResult::critical(string $name, string $message, array $meta)`Failing result`$result->withMetrics(array $metrics): CheckResult`Attach metrics to a result### `HealthReport`

[](#healthreport)

MethodReturn TypeDescription`$report->status``HealthStatus`Overall status enum`$report->isHealthy()``bool``true` when status is `Ok``$report->getMetrics()``array`Aggregated metrics from all checks`$report->toArray()``array`Full report as array`$report->toJson(int $flags)``string`Full report as JSONDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/laravel-healthcheck)

🐛 [Report issues](https://github.com/philiprehberger/laravel-healthcheck/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/laravel-healthcheck/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance87

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 92.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

9

Last Release

97d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (24 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

laravelmonitoringhealthhealthcheckkubernetesk8s

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-laravel-healthcheck/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-laravel-healthcheck/health.svg)](https://phpackages.com/packages/philiprehberger-laravel-healthcheck)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77018.2M120](/packages/laravel-mcp)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)[laravel/surveyor

Static analysis tool for Laravel applications.

8690.3k12](/packages/laravel-surveyor)[fleetbase/core-api

Core Framework and Resources for Fleetbase API

1232.2k16](/packages/fleetbase-core-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
