Monday, February 21, 2022

[SOLVED] Pass optional arrgument Laravel 5.8, cron job

Issue

protected $signature = 'do_command {import=false}';
public function handle(){
    $import= $this->argument('import');

    if($import){
        // do something else
    }

}

and I am using it in the controller and NOT only:

    $command = 'do_command';
    $option = null;
    if($import){
        $option = 'import';
    }
    Artisan::call($command, [$option]);

The problem is, it doesn't matter, if $import in the controller is true/false, if statement is always executed and $this->argument('import') is always true in handle method, even if I call Artisan::call($command) without second argument.


Solution

You are defining the default value of import as false, which would be a string. Therefore, the if condition in your command will always be true:

if ($import) {
    // 
}

What you could do is change the signature to have the import option as optional.

protected $signature = 'command:name {import?}';

Then in your controller:

Artisan::call($command, [
    'import' => $import,
]);


Answered By - Chin Leung
Answer Checked By - Terry (WPSolving Volunteer)