Start by installing the package via Composer:
composer require queents/console-helpers
First Use Case: Replace a manual shell_exec call in an Artisan command with the RunCommand trait.
use Queents\ConsoleHelpers\Traits\RunCommand;
class MyCommand extends Command {
use RunCommand;
}
shell_exec('php artisan migrate') with:
$this->artisanCommand('migrate');
Where to Look First:
config/console-helpers.php (if created) for configurable paths (e.g., Yarn).Pattern: Use traits to centralize CLI logic in Artisan commands.
// In a deployment command
$this->yarnCommand('install --dev');
$this->phpCommand('artisan optimize:clear');
$this->artisanCommand('migrate --force');
Workflow:
config('console-helpers.yarn_path').$this->call() or $this->handle() for async workflows.$exitCode = $this->phpCommand('php -v', true); // Returns exit code
if ($exitCode !== 0) { $this->error('PHP command failed'); }
Pattern: Generate dynamic files (e.g., API clients, config files) from stubs.
$this->generateStubs(
__DIR__.'/stubs/UserModel.stub',
app_path('Models/User.php'),
['namespace' => 'App\Models'],
[app_path('Models/')] // Ensure directory exists
);
Workflow:
resources/stubs/ or a module-specific directory.Str::lower() or Str::title() for dynamic replacements.Pattern: Toggle modules in bulk or per-module (requires laravel-modules).
// Activate all modules
$this->activeAllModules();
// Deactivate a specific module
$this->activeModule('Admin', false);
Workflow:
HandleStubs to generate module-specific configs:
$this->activeModule('Auth');
$this->generateStubs('stubs/AuthConfig.stub', ...);
Pattern: Use traits alongside Laravel’s built-in tools.
// Hybrid approach: Use Process facade for complex commands
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
try {
$process = new Process(['php', 'artisan', 'queue:work']);
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
} catch (ProcessFailedException $e) {
$this->error($e->getMessage());
}
When to Use Which:
| Tool | Use Case | Example |
|---|---|---|
RunCommand trait |
Simple, trusted commands (e.g., yarn build) |
$this->yarnCommand('build') |
Process facade |
Complex commands (timeouts, logging) | Process::of('php artisan ...')->run() |
Artisan::call() |
Internal Laravel commands | Artisan::call('migrate') |
Shell Injection Vulnerabilities:
$this->phpCommand('user_input') executes arbitrary shell code.Process facade:
$process = new Process(['php', 'artisan', 'migrate'], null, null, null, 60);
$process->run();
Stub Path Resolution:
generateStubs() fails if directories don’t exist.$path = app_path('Models/User.php');
if (!file_exists(dirname($path))) {
mkdir(dirname($path), 0755, true);
}
Module Management Assumptions:
HandleModules assumes laravel-modules is installed and configured.if (!class_exists(\NWidart\Modules\Module::class)) {
$this->error('laravel-modules is required for module commands.');
return 1;
}
Exit Code Ignorance:
$this->artisanCommand('migrate') silently fails if migration errors occur.$exitCode = $this->artisanCommand('migrate', true);
if ($exitCode !== 0) { $this->error('Migrations failed'); }
Yarn Path Configuration:
yarnCommand fails if Yarn isn’t in PATH or config isn’t set.config/console-helpers.php:
'yarn_path' => '/usr/local/bin/yarn',
$this->phpCommand('php -v', true, function ($type, $buffer) {
$this->line($buffer);
});
php artisan command:test to validate stub generation or module toggling.Customize Command Execution:
RunCommand trait to add timeouts or logging:
protected function phpCommand(string $command, bool $returnOutput = false, ?Closure $callback = null): int|string {
$process = new Process(['php', '-r', $command], null, null, null, 30); // 30s timeout
$process->run($callback);
return $process->isSuccessful() ? 0 : $process->getOutput();
}
Add Stub Placeholders:
HandleStubs to support nested arrays or custom delimiters:
$this->generateStubs(
'stub.stub',
'output.php',
['data' => ['key' => 'value']],
[app_path()]
);
Module Lifecycle Hooks:
$this->activeModule('Auth', true, function () {
$this->info('Auth module activated. Running post-activation tasks...');
});
config/console-helpers.php by default. Create it manually:
return [
'yarn_path' => env('YARN_PATH', 'yarn'),
'php_path' => env('PHP_PATH', 'php'),
];
yarn build):
dispatch(new BuildYarnAssets)->onQueue('yarn');
$cacheKey = 'stub_output_' . md5($stubPath);
if (Cache::has($cacheKey)) {
return Cache::get($cacheKey);
}
$output = $this->generateStubs(...);
Cache::put($cacheKey, $output, now()->addHours(1));
How can I help you explore Laravel packages today?