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

Health Check Laravel Package

bayzet/health-check

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bayzet/health-check
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Bayzet\HealthCheck\HealthCheckServiceProvider::class,
    ],
    
  2. Basic Usage Define a health check in a service provider or boot method:

    use Bayzet\HealthCheck\Facades\HealthCheck;
    
    public function boot()
    {
        HealthCheck::addCheck('database', function () {
            return DB::connection()->getPdo();
        });
    }
    
  3. First Endpoint Add a route to trigger checks:

    Route::get('/health', [HealthCheckController::class, 'check']);
    

    (Note: The package doesn’t include a controller; you’ll need to create one.)


Implementation Patterns

1. Check Registration

  • Dynamic Checks: Register checks in boot() or via events (e.g., registered).
    HealthCheck::addCheck('cache', function () {
        return Cache::getStore()->get('test');
    });
    
  • Named Checks: Use descriptive names (e.g., database_connection, queue_worker).

2. Check Logic

  • Return Types:
    • true/false for pass/fail.
    • Throw exceptions for failures (automatically marked as failed).
    HealthCheck::addCheck('storage', function () {
        if (!Storage::disk('local')->exists('health-check.txt')) {
            throw new \RuntimeException('Storage check failed');
        }
        return true;
    });
    

3. Grouping Checks

  • Use tags to group related checks (e.g., ['tag' => 'database']).
  • Filter results by tag in your endpoint:
    $results = HealthCheck::check(['tag' => 'database']);
    

4. Integration with Laravel

  • Middleware: Use checks in middleware to block requests if critical services fail.
    public function handle($request, Closure $next)
    {
        if (!HealthCheck::check(['tag' => 'auth'])) {
            abort(503);
        }
        return $next($request);
    }
    
  • Commands: Run checks via Artisan:
    Artisan::call('health:check', ['--tag' => 'database']);
    

5. Custom Responses

  • Override the default response format:
    $results = HealthCheck::check();
    return response()->json([
        'status' => 'healthy',
        'checks' => $results,
    ]);
    

Gotchas and Tips

Pitfalls

  1. No Built-in Controller/Route:

    • The package lacks a default endpoint or controller. You must implement this yourself.
    • Example minimal controller:
      public function check()
      {
          $results = HealthCheck::check();
          return response()->json($results);
      }
      
  2. No Persistent Storage:

    • Results are in-memory. For historical data, log results to a database or file.
  3. No Built-in Scheduling:

    • Use Laravel’s scheduler to run checks periodically:
      $schedule->command('health:check')->everyMinute();
      
  4. Exception Handling:

    • Uncaught exceptions in checks will crash the request. Wrap logic in try-catch if needed.

Debugging Tips

  • Check Registration: Use HealthCheck::getChecks() to verify registered checks.
  • Isolate Checks: Test checks individually by temporarily disabling others.
  • Logging: Log check results for debugging:
    HealthCheck::addCheck('logs', function () {
        \Log::info('Log check passed');
        return true;
    });
    

Extension Points

  1. Custom Check Classes: Extend the Bayzet\HealthCheck\Check class for reusable logic:

    class DatabaseCheck extends Check
    {
        public function run()
        {
            return DB::connection()->getPdo() !== false;
        }
    }
    

    Register via:

    HealthCheck::addCheck(new DatabaseCheck('database'));
    
  2. Custom Response Formatters: Override the HealthCheck facade to modify output:

    HealthCheck::extend(function ($app) {
        $app->resolving('health.check', function ($check) {
            // Modify response logic here
        });
    });
    
  3. Dependency Injection: Inject dependencies into checks via closure binding:

    HealthCheck::addCheck('mail', function ($mailer) {
        return $mailer->mailer->getTransport();
    })->with(\Illuminate\Mail\Mailer::class);
    

Performance Considerations

  • Avoid Heavy Operations: Keep checks lightweight (e.g., avoid long-running queries).
  • Cache Results: Cache results if checks are expensive (e.g., external API calls).
    $results = Cache::remember('health_check_results', now()->addMinutes(5), function () {
        return HealthCheck::check();
    });
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware