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

Ping Laravel Package

spatie/ping

Run ICMP ping from PHP and get structured results. Spatie Ping wraps the system ping command, parsing packet loss, transmit/receive counts, min/max/avg times, standard deviation, per-line responses, and error status for quick connectivity checks.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/ping
    

    No additional configuration is required—just autoload.

  2. First Ping:

    use Spatie\Ping\Ping;
    
    $result = Ping::to('google.com')->ping();
    

    Outputs a structured result with:

    • success (bool)
    • latency (ms)
    • packetLoss (int)
    • error (string|null)
  3. Key Files:

    • vendor/spatie/ping/src/Ping.php (core class)
    • vendor/spatie/ping/tests/ (test cases for edge cases)

First Use Case: Uptime Monitoring

$ping = Ping::to('example.com');
if ($ping->ping()->success) {
    // Log success or trigger notification
}

Implementation Patterns

Common Workflows

  1. Batch Pinging:

    $hosts = ['google.com', 'github.com', 'spatie.be'];
    $results = collect($hosts)->map(fn($host) => Ping::to($host)->ping());
    

    Useful for monitoring multiple endpoints.

  2. Retry Logic:

    $attempts = 3;
    $result = null;
    while ($attempts--) {
        $result = Ping::to('flaky-service.com')->ping();
        if ($result->success) break;
    }
    
  3. Latency Thresholds:

    $ping = Ping::to('api.example.com')->ping();
    if ($ping->latency > 500) {
        // Alert on high latency
    }
    

Integration Tips

  • Queue Jobs:

    Ping::to('critical-service.com')->ping()->then(function ($result) {
        if (!$result->success) {
            dispatch(new NotifyAdmins($result->error));
        }
    });
    

    Use Laravel’s queue system to avoid blocking requests.

  • Caching Results:

    $cacheKey = 'ping:google.com';
    $result = Cache::remember($cacheKey, now()->addMinutes(5), function () {
        return Ping::to('google.com')->ping();
    });
    
  • Logging:

    Ping::to('db.example.com')->ping()->then(function ($result) {
        Log::info('Ping result', ['host' => 'db.example.com', 'success' => $result->success]);
    });
    

Gotchas and Tips

Pitfalls

  1. Firewall/Network Restrictions:

    • Some hosts block ICMP (ping). Fallback to HTTP checks if needed:
      $response = Http::get('https://example.com/health')->throw();
      
  2. Timeout Handling:

    • Default timeout is 2 seconds. Adjust with:
      Ping::to('slow-host.com')->timeout(5); // 5 seconds
      
  3. DNS Resolution:

    • Ping resolves hostnames to IPs. For direct IP checks:
      Ping::to('8.8.8.8')->ping(); // Skip DNS lookup
      
  4. Packet Loss Interpretation:

    • packetLoss is a percentage. A value of 0 means no loss, but null may indicate an error (e.g., unreachable host).

Debugging

  • Verbose Output: Enable debug mode to see raw ICMP output (not officially supported, but you can inspect the underlying exec calls via Ping::to('host')->debug()).

  • Common Errors:

    • "Command not found": Ensure ping is installed on the server (Linux/macOS: ping, Windows: ping.exe).
    • "Permission denied": Run Laravel’s queue worker with sufficient privileges.

Extension Points

  1. Custom Ping Commands: Override the default ping command for specific use cases (e.g., TCP port checks):

    use Spatie\Ping\Ping;
    
    class CustomPing extends Ping {
        protected function getCommand(): string {
            return 'ping -c 1 -W 2 ' . $this->host;
        }
    }
    
  2. Event Dispatching: Trigger events on ping results:

    Ping::to('monitor.com')->ping()->then(function ($result) {
        event(new PingResult($result));
    });
    
  3. Testing: Mock Ping in tests:

    Ping::shouldReceive('ping')->andReturn((object) ['success' => true, 'latency' => 100]);
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport