Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Health Laravel Package

spatie/laravel-health

Monitor your Laravel app’s health by registering configurable checks (disk space, queues, cache, etc.). Get warnings or failures and receive notifications via mail or Slack, with an easy API for adding custom checks and reporting status.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-health
    

    Publish the config file:

    php artisan vendor:publish --tag="health-config"
    
  2. First Check: Register a basic check in a service provider (e.g., AppServiceProvider):

    use Spatie\Health\Facades\Health;
    use Spatie\Health\Checks\Checks\DatabaseConnectionCheck;
    
    Health::checks([
        DatabaseConnectionCheck::new(),
    ]);
    
  3. View Results: Add the health route to your routes/web.php:

    use Spatie\Health\Facades\Health;
    
    Health::routes();
    

    Visit /health to see the dashboard.


First Use Case: Monitoring Disk Space

use Spatie\Health\Facades\Health;
use Spatie\Health\Checks\Checks\UsedDiskSpaceCheck;

Health::checks([
    UsedDiskSpaceCheck::new()
        ->warnWhenUsedSpaceIsAbovePercentage(70)
        ->failWhenUsedSpaceIsAbovePercentage(90),
]);
  • Trigger: Automatically runs on cron or manual request to /health.
  • Notifications: Configured via config/health.php (e.g., Slack, email).

Implementation Patterns

1. Registering Checks

  • Default Checks: Use built-in checks (e.g., DatabaseConnectionCheck, QueueCheck).
    Health::checks([
        DatabaseConnectionCheck::new(),
        QueueCheck::new()->failWhenJobsAreBehindBy(100),
    ]);
    
  • Custom Checks: Extend Spatie\Health\Checks\Check:
    use Spatie\Health\Checks\Check;
    use Spatie\Health\Result;
    
    class CustomCheck extends Check
    {
        public function perform(): Result
        {
            if ($this->someCondition()) {
                return Result::fail('Custom failure message');
            }
            return Result::ok();
        }
    }
    
    Register it:
    Health::checks([new CustomCheck()]);
    

2. Notification Workflows

  • Configure Channels: Update config/health.php:
    'notifications' => [
        Spatie\Health\Notifications\CheckFailedNotification::class => ['mail', 'slack'],
    ],
    
  • Throttling: Adjust throttle_notifications_for_minutes (default: 60).
  • Conditional Notifications: Use only_on_failure to ignore warnings:
    'notifications' => [
        'enabled' => true,
        'only_on_failure' => true,
    ],
    

3. Oh Dear Integration

  • Enable Endpoint:
    // config/health.php
    'oh_dear_endpoint' => [
        'enabled' => true,
        'secret' => env('OH_DEAR_HEALTH_CHECK_SECRET'),
        'url' => '/oh-dear-health-check-results',
    ],
    
  • Disable Local Notifications:
    'notifications' => ['enabled' => false],
    
  • Use In-Memory Store (for ephemeral environments):
    'result_stores' => [
        Spatie\Health\ResultStores\InMemoryHealthResultStore::class,
    ],
    

4. Cron Jobs

Add to your cron schedule (e.g., app/Console/Kernel.php):

protected function schedule(Schedule $schedule)
{
    $schedule->command('health:check')->hourly();
}

Run checks manually:

php artisan health:check

Gotchas and Tips

Pitfalls

  1. Duplicate Check Names:

    • Default names are class names (e.g., DatabaseConnectionCheck). Override with:
      DatabaseConnectionCheck::new()->name('Production DB Check')
      
    • Fix: Use unique names for repeated checks (e.g., PingCheck for multiple URLs).
  2. Secret Token Misconfiguration:

    • If using /health publicly, ensure the secret_token is set in config/health.php:
      'secret_token' => env('HEALTH_SECRET_TOKEN'),
      
    • Tip: Restrict access via middleware or firewall rules.
  3. Notification Delays:

    • Throttling may delay alerts. Adjust throttle_notifications_for_minutes or disable for critical checks:
      'notifications' => ['throttle_notifications_for_minutes' => 5],
      
  4. Oh Dear Sync Issues:

    • If always_send_fresh_results is false, Oh Dear may show stale data. Set to true for real-time updates:
      'oh_dear_endpoint' => ['always_send_fresh_results' => true],
      

Debugging Tips

  1. Check Results Manually:

    php artisan health:check --verbose
    
    • Outputs detailed results to the terminal.
  2. Inspect Config:

    php artisan config:dump Spatie\Health\HealthServiceProvider
    
    • Verify published config values.
  3. Test Notifications:

    • Use php artisan notify:send with a test notification class to validate channels.
  4. Log Health Checks:

    • Add a custom check to log results:
      class LogCheck extends Check
      {
          public function perform(): Result
          {
              \Log::info('Health check performed', ['result' => $this->result()]);
              return $this->result();
          }
      }
      

Extension Points

  1. Custom Result Stores:

    • Implement Spatie\Health\ResultStores\HealthResultStore to persist results (e.g., database):
      class DatabaseHealthResultStore implements HealthResultStore
      {
          public function store(HealthResult $result): void
          {
              // Save to DB
          }
      }
      
    • Register in config/health.php:
      'result_stores' => [App\ResultStores\DatabaseHealthResultStore::class],
      
  2. Dynamic Checks:

    • Load checks from config or environment:
      $checks = config('health.checks', []);
      Health::checks(array_map(fn ($check) => $check::new(), $checks));
      
  3. Webhook Triggers:

    • Extend the package to trigger checks via HTTP POST:
      Route::post('/trigger-health-check', function () {
          $result = Health::checkNow();
          return response()->json($result);
      });
      
  4. Slack/Discord Rich Messages:

    • Customize notification templates by extending CheckFailedNotification:
      use Spatie\Health\Notifications\CheckFailedNotification;
      
      class CustomCheckFailedNotification extends CheckFailedNotification
      {
          public function toSlack($notifiable)
          {
              return 'Custom Slack message: ' . $this->message;
          }
      }
      
    • Update config/health.php:
      'notifications' => [
          App\Notifications\CustomCheckFailedNotification::class => ['slack'],
      ],
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai