Run Another Command From Artisan Command in Laravel 10

Run Another Command From Artisan Command in Laravel 10

Laravel provides the Artisan command line interface for developers to manage various aspects of their applications. One of the convenient features of Artisan is the ability to run other commands from an existing Artisan command. This can be particularly useful when you want to automate certain tasks or create more complex workflows. This tutorial shows how to run another command from Artisan command in Laravel 10.

Imagine a situation involving two commands within the Laravel application: app:demo and app:test. The app:demo command requires a mandatory argument, namely, the username, and also supports an optional --create option.

app/Console/Commands/DemoCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class DemoCommand extends Command
{
    protected $signature = 'app:demo {username} {--create}';

    public function handle(): int
    {
        $this->line($this->argument('username'));
        $this->line($this->option('create'));

        return Command::SUCCESS;
    }
}

The purpose of the app:test command is to programmatically trigger the execution of the app:demo command.

In the app:test command, we create an array to hold input arguments and options for the app:demo command. By using the call method, we execute the app:demo command with the provided input, obtaining the corresponding exit code.

app/Console/Commands/TestCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TestCommand extends Command
{
    protected $signature = 'app:test';

    public function handle(): int
    {
        $cmdInput = [
            'username' => 'john',
            '--create' => true,
        ];

        $returnCode = $this->call('app:demo', $cmdInput);
        $this->line($returnCode);

        return Command::SUCCESS;
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.