Run External CLI Commands from Laravel with Process::path()

📖 2 minutes read

Laravel’s Process facade makes it easy to run external command-line tools from your PHP application. The path() method is especially useful when you need to execute commands in a specific working directory.

Basic Usage

use Illuminate\Support\Facades\Process;

// Run a script from a specific directory
Process::path('/opt/scripts')
    ->run(['./backup.sh', '--full'])
    ->throw();

The path() method changes the working directory before executing the command. This is crucial when scripts depend on relative paths or expect to run from a specific location.

Real-World Example: Integration Scripts

Imagine you’re integrating with an external CLI tool installed in a separate directory:

class DataSyncService
{
    public function syncUser(User $user): void
    {
        $command = [
            'bin/sync-tool',
            'user',
            'update',
            $user->email,
            '--name=' . $user->name,
            '--active=' . ($user->is_active ? 'true' : 'false'),
        ];

        Process::path(config('services.sync.install_path'))
            ->run($command)
            ->throw();  // Throws ProcessFailedException on non-zero exit
    }
}

Key Features

  • path($directory): Set working directory
  • run($command): Execute and return result
  • throw(): Fail loudly on errors
  • timeout($seconds): Prevent hanging

With Timeout Protection

$result = Process::path('/var/tools')
    ->timeout(30)  // Kill after 30 seconds
    ->run(['./long-task.sh'])
    ->throw();

echo $result->output();

Handling Output

$result = Process::path('/opt/reports')
    ->run(['./generate-report.sh', '--format=json']);

if ($result->successful()) {
    $data = json_decode($result->output(), true);
    // Process the data...
} else {
    Log::error('Report generation failed: ' . $result->errorOutput());
}

This pattern is especially useful when integrating third-party tools, running system utilities, or coordinating with non-PHP services that expose CLI interfaces.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *