How To Programmatically Execute Command In Laravel

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

Artisan is the command-line interface included with Laravel. It provides a number of helpful commands that can assist you while you build your application.

How To Programmatically Execute Command In Laravel

Programmatically Executing Commands

Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to fire an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The call method accepts either the command's name or class as the first argument, and an array of command parameters as the second argument. The exit code will be returned:

Route::get('/test', function () {
$exitCode = Artisan::call('email:send', [
'user' => 1, '--queue' => 'default'
]);

//
});
 

Alternatively, you may pass the entire Artisan command to the call method as a string:

Artisan::call('email:send 1 --queue=default');


Using the queue method on the Artisan facade, you may even queue Artisan commands so they are processed in the background by your queue workers. Before using this method, make sure you have configured your queue and are running a queue listener:

Route::get('/test', function () {
    Artisan::queue('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
});

You may also specify the connection or queue the Artisan command should be dispatched to:

Artisan::queue('email:send', [
    'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');
 


Passing Array Values

If your command defines an option that accepts an array, you may pass an array of values to that option:

Route::get('/test', function () {
    $exitCode = Artisan::call('email:send', [
        'user' => 1, '--id' => [5, 13]
    ]);
});


Passing Boolean Values

$exitCode = Artisan::call('migrate:refresh', [
    '--force' => true,
]);


Calling Commands From Other Commands

Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the call method. This call method accepts the command name and an array of command parameters:

/**
 * Execute the console command.
 *
 * @return mixed
 */
public function handle()
{
    $this->call('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);

    //
}

 

If you would like to call another console command and suppress all of its output, you may use the callSilent method. The callSilent method has the same signature as the call method:

$this->callSilent('email:send', [
    'user' => 1, '--queue' => 'default'
]);

Related Post