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 Remote Laravel Package

spatie/laravel-remote

Run Laravel Artisan commands on remote servers over SSH. Configure one or more hosts (default host, user, port, path, optional private key) and execute tasks like cache clears via php artisan remote ..., with optional confirmation prompts.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/laravel-remote
    php artisan vendor:publish --tag="remote-config"
    

    Publish the config file to customize remote server connections.

  2. Define Remote Servers: Edit config/remote.php to define your remote servers under the servers key:

    'servers' => [
        'production' => [
            'host' => 'user@your-server.com',
            'port' => 22,
            'key' => '/path/to/private/key',
            'options' => [
                '-o', 'StrictHostKeyChecking=no',
            ],
        ],
    ],
    
  3. First Use Case: Execute an Artisan command on a remote server:

    php artisan remote:run production cache:clear
    

    This runs cache:clear on the production server.


Where to Look First

  • Config File: config/remote.php – Define and manage remote servers.
  • Artisan Commands:
    • remote:run – Execute a single command.
    • remote:queue – Queue a command for later execution.
    • remote:queue:run – Run queued commands.
  • Documentation: The README includes examples and setup instructions.

Implementation Patterns

Usage Patterns

  1. Direct Command Execution: Use remote:run for immediate, one-off tasks:

    php artisan remote:run production migrate
    
  2. Queued Commands: Schedule commands for later execution (e.g., during off-peak hours):

    php artisan remote:queue production optimize:clear
    php artisan remote:queue:run production
    
  3. Environment-Specific Workflows: Define servers in remote.php with environment-specific configurations (e.g., staging, production):

    'servers' => [
        'staging' => [
            'host' => 'user@staging.example.com',
            'key' => storage_path('keys/staging_key'),
        ],
        'production' => [
            'host' => 'user@prod.example.com',
            'key' => storage_path('keys/prod_key'),
        ],
    ],
    

    Run commands dynamically:

    php artisan remote:run staging deploy:prepare
    
  4. Integration with Deployment Scripts: Use remote:run in deployment pipelines (e.g., Laravel Forge, Deployer) to trigger post-deploy tasks:

    php artisan remote:run production queue:restart
    php artisan remote:run production supervisor:restart
    
  5. Custom Artisan Commands: Extend the package by creating custom commands that leverage Remote:

    use Spatie\Remote\Remote;
    
    class MyCustomCommand extends Command
    {
        protected $signature = 'my:remote-task {server}';
    
        public function handle()
        {
            Remote::run($this->argument('server'), 'my:custom-command');
        }
    }
    

Workflows

  1. Zero-Downtime Deployments:

    • Queue database migrations and cache clearing for execution after deployment:
      php artisan remote:queue production migrate --force
      php artisan remote:queue production cache:clear
      
    • Run queued tasks post-deploy:
      php artisan remote:queue:run production
      
  2. Monitoring and Maintenance:

    • Schedule regular maintenance tasks (e.g., queue pruning, storage cleanup):
      php artisan remote:queue production queue:prune --hours=1
      
  3. Multi-Server Coordination:

    • Execute commands across multiple servers in parallel:
      php artisan remote:run production queue:restart
      php artisan remote:run staging queue:restart
      

Integration Tips

  1. SSH Key Management:

    • Store private keys securely (e.g., storage/app/keys/ or a secrets manager).
    • Use environment variables for sensitive paths:
      'key' => env('REMOTE_SSH_KEY_PATH'),
      
  2. Error Handling:

    • Wrap Remote::run() in try-catch blocks to handle failures gracefully:
      try {
          Remote::run('production', 'my:command');
      } catch (\Exception $e) {
          Log::error("Remote command failed: {$e->getMessage()}");
      }
      
  3. Logging:

    • Enable verbose output for debugging:
      php artisan remote:run production --verbose migrate
      
    • Log remote command outputs to Laravel logs:
      Remote::run('production', 'my:command', function ($output) {
          Log::info($output);
      });
      
  4. Environment Variables:

    • Pass environment variables to remote commands:
      php artisan remote:run production my:command --env=production
      
  5. Artisan Command Options:

    • Forward options to remote commands:
      php artisan remote:run production migrate --force --seed
      

Gotchas and Tips

Pitfalls

  1. SSH Key Permissions:

    • Ensure SSH keys have correct permissions (chmod 600 for private keys). Failing this will result in connection errors.
  2. StrictHostKeyChecking:

    • If you encounter Host key verification failed, add -o StrictHostKeyChecking=no to the options array in the config. Use cautiously in production.
  3. Command Timeouts:

    • Long-running commands may time out. Adjust the SSH timeout in the config or use screen/tmux for persistent sessions:
      'options' => [
          '-o', 'ConnectTimeout=30',
          '-o', 'ServerAliveInterval=60',
      ],
      
  4. Command Output Buffering:

    • Remote commands may buffer output. Use --verbose or callback functions to stream output in real-time:
      Remote::run('production', 'my:command', function ($output) {
          echo $output;
      });
      
  5. Dependency Conflicts:

    • Ensure the remote server has compatible PHP/Laravel versions. Test commands locally before remote execution.
  6. Queued Command Order:

    • Queued commands run in the order they are added. Use remote:queue:run --force to bypass order for critical tasks.

Debugging

  1. SSH Debugging:

    • Enable verbose SSH output by adding -vvv to the options array:
      'options' => [
          '-vvv',
      ],
      
  2. Command Output:

    • Redirect output to a file for debugging:
      php artisan remote:run production my:command > remote_output.log 2>&1
      
  3. Dry Runs:

    • Test connections without executing commands:
      php artisan remote:test production
      
  4. Logging:

    • Enable Laravel debug mode (APP_DEBUG=true) to log remote command interactions.

Config Quirks

  1. Dynamic Server Configuration:

    • Override server configurations dynamically using environment variables:
      'servers' => [
          'production' => [
              'host' => env('REMOTE_PROD_HOST', 'default@example.com'),
          ],
      ],
      
  2. Default Server:

    • Set a default server in the config to avoid specifying it repeatedly:
      'default_server' => 'production',
      
    • Then run commands without the server argument:
      php artisan remote:run cache:clear
      
  3. Key Paths:

    • Use absolute paths for SSH keys to avoid resolution issues:
      'key' => '/home/user/.ssh/production_key',
      

Extension Points

  1. Custom Remote Adapters:

    • Extend the package to support non-SSH protocols (e.g., HTTP APIs) by implementing a custom RemoteAdapter.
  2. Pre/Post Command Hooks:

    • Add logic before/after command execution by extending the Remote facade or creating a decorator:
      Remote::extend(function ($remote) {
          $remote->before(function () {
              Log::info('Running pre-command hooks');
          });
      
          return $remote;
      });
      
  3. Command Validation:

    • Validate remote servers or commands before execution:
      if (!Remote::serverExists('production')) {
          throw new \Exception('Server not configured');
      }
      
  4. Parallel Execution:

    • Use Laravel's parallel helper to run commands on multiple servers concurrently:
      parallel([
          'production' => fn() => Remote::run('production', 'queue:restart'),
          'staging' => fn() => Remote::run('staging', 'queue:restart'),
      ]);
      
  5. Webhooks for Queued Commands:

    • Trigger webhooks when queued commands complete by extending the RemoteQueue class:
      RemoteQueue::addListener('production', function ($result) {
      
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