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 Live Terminal Laravel Package

tanbhirhossain/laravel-live-terminal

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require tanbhirhossain/laravel-live-terminal
    php artisan vendor:publish --provider="TanbhirHossain\LiveTerminal\LiveTerminalServiceProvider" --tag="config"
    
  2. Configure config/live-terminal.php:
    'allowed_commands' => [
        'migrate',
        'migrate:fresh',
        'db:seed',
        'cache:clear',
        'route:list',
    ],
    'auth_middleware' => ['auth:sanctum'], // or 'auth:admin'
    
  3. Route Access: Add to routes/web.php:
    Route::middleware(['web', 'auth:sanctum'])->get('/terminal', [\TanbhirHossain\LiveTerminal\Http\Controllers\TerminalController::class, 'index']);
    
  4. First Use Case: Visit /terminal in your browser to execute whitelisted Artisan commands (e.g., php artisan migrate).

Implementation Patterns

Workflows

  1. Command Whitelisting:

    • Static Whitelist: Define allowed commands in config/live-terminal.php (e.g., ['migrate', 'queue:work']).
    • Dynamic Whitelist: Extend via service provider:
      public function boot()
      {
          $this->app['live-terminal']->extend(function ($terminal) {
              $terminal->allowedCommands(['tinker']); // Add dynamically
          });
      }
      
    • Environment-Specific: Use .env to toggle features:
      LIVE_TERMINAL_ENABLED=true
      LIVE_TERMINAL_ALLOWED_COMMANDS=migrate,db:seed
      
  2. Middleware Integration:

    • Role-Based Access: Combine with spatie/laravel-permission:
      Route::middleware(['auth:sanctum', 'can:access-terminal'])->get('/terminal', ...);
      
    • IP Whitelisting: Add middleware to restrict by IP:
      Route::middleware(['web', 'auth:sanctum', 'trusted'])->get('/terminal', ...);
      
  3. Output Handling:

    • Real-Time Updates: Leverage Laravel Echo/Pusher for live command output (extend TerminalController).
    • Logging: Log terminal usage to storage/logs/terminal.log:
      $terminal->logCommand('migrate', $user->id, $output);
      
  4. Command Arguments:

    • Safe Argument Parsing: Whitelist arguments in config:
      'allowed_commands' => [
          'migrate' => ['args' => ['--force']],
          'db:seed' => ['args' => ['--class=UserSeeder']],
      ],
      
    • Dynamic Arguments: Use a closure to validate args:
      'allowed_commands' => [
          'queue:work' => ['args' => function ($args) {
              return in_array($args[0] ?? '', ['--once', '--sleep=3']);
          }],
      ],
      
  5. Integration with Laravel Features:

    • Horizon Monitoring: Add a command to check Horizon status:
      'allowed_commands' => ['horizon:status'],
      
    • Queue Management: Whitelist queue:work and queue:flush.

Gotchas and Tips

Pitfalls

  1. Security Misconfigurations:

    • Unrestricted Access: Always enforce middleware (e.g., auth:sanctum). Avoid public routes.
    • Dangerous Commands: Never allow:
      ['allowed_commands' => ['artisan', 'exec', 'shell']] // ❌ Avoid!
      
    • File System Risks: Block commands like storage:link, down, or up unless explicitly needed.
  2. Command Output Issues:

    • Buffering Delays: Use --no-ansi for commands with slow output (e.g., queue:work).
    • Memory Limits: Add ini_set('memory_limit', '512M') to the terminal’s TerminalController for heavy commands.
  3. Configuration Overrides:

    • Environment Conflicts: Ensure .env and config/live-terminal.php don’t override each other unexpectedly. Use:
      'allowed_commands' => explode(',', env('LIVE_TERMINAL_ALLOWED_COMMANDS', 'migrate,db:seed')),
      
  4. Middleware Conflicts:

    • Route Caching: Clear cached routes after adding middleware:
      php artisan route:clear
      
    • Guest Access: Test with php artisan route:list | grep terminal to verify middleware.

Debugging

  1. Command Failures:

    • Check storage/logs/laravel.log for Artisan errors.
    • Enable debug mode in config/live-terminal.php:
      'debug' => env('APP_DEBUG', false),
      
  2. Output Formatting:

    • ANSI escape sequences may break in browsers. Use:
      $output = str_replace("\e[", '', $output); // Strip ANSI for web
      
  3. Permission Denied:

    • Ensure the web server user (e.g., www-data) has execute permissions for Artisan:
      chmod +x artisan
      

Tips

  1. Custom Terminal UI:

    • Extend the Blade view (resources/views/vendor/live-terminal/index.blade.php) to add:
      • Command history (store in sessions).
      • Syntax highlighting for Artisan commands.
      • Dark mode support.
  2. Rate Limiting:

    • Add throttle middleware to prevent abuse:
      Route::middleware(['throttle:60,1'])->get('/terminal', ...);
      
  3. Team Collaboration:

    • Log terminal sessions with user IDs:
      $terminal->log(['user_id' => auth()->id(), 'command' => $command, 'output' => $output]);
      
    • Integrate with Slack/Teams for alerts on critical commands (e.g., migrate:fresh).
  4. Performance Optimization:

    • Command Caching: Cache frequent commands (e.g., route:list) for 5 minutes:
      $cacheKey = "terminal_route_list_{$user->id}";
      return Cache::remember($cacheKey, 300, fn() => Artisan::call('route:list'));
      
    • Lazy Loading: Load the terminal UI only for admin users via JavaScript:
      if (userIsAdmin) {
          fetch('/terminal').then(html => document.getElementById('terminal').innerHTML = html);
      }
      
  5. Testing:

    • Unit Tests: Mock the TerminalController:
      $terminal = Mockery::mock(\TanbhirHossain\LiveTerminal\Terminal::class);
      $terminal->shouldReceive('execute')->with('migrate')->andReturn('Success!');
      
    • Browser Tests: Use Laravel Dusk to simulate terminal usage:
      $browser->visit('/terminal')->type('migrate')->press('Enter');
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
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