php - Artisan::call command package throws error exception will calling through web page ← (PHP, Laravel, Symfony)

I'm using docker for running a Laravel project and i have this command in Laravel that writes into a file in storage folder

Artisan::call(
    'app:cache',
    [
        "--message" => 'this is a command', 
        "--seconds" => 0
    ]
)

when i call it through web like

Route::get('/', function () {
    \Artisan::call(
        'app:cache',
        [
            "--message" => 'this is a command', 
            "--seconds" => 0
        ]
    );
});

an exception from /src/vendor/symfony/console/Input/ArrayInput.php file is generated with this message: "Trying to access array offset on value of type int"

but in command line this command is working completely OK.

Answer



Solution:

the issue was coming from my using version of PHP, the PHP version was 7.4.1 and the package that Laravel was using for this version of PHP was changed and that caused the error to happen, I changed my using PHP version to 7.2 and got worked. I have been given the code but normally, programmers should not use this kind of packages this way, for example in this one, WEB should not call Artisan commands directly, because if a situation like this happens you will need to override your code like everywhere. Instead, use your own code and put what you want behind it, as an example:

imaging you have this artisan command that writes some information in a file and you want to use it in your WEB section then you must put your code into a class or function outside of your artisan command and use your class/function in your artisan and web for work. then code like bellow

Route::get('/', function () {
    \Artisan::call(
        'app:cache',
        [
            "--message" => 'this is a command', 
            "--seconds" => 0
        ]
    );
});

will become to code like

Route::get('/', function () {
    $cache = new \App\Custom\Cache(
        $message = 'this is a command',
        $seconds = 0
    );
});

In this way, your functioning code is separated from your framework and if you even use some packages in your class/function and a package needs to change like it was to call Artisan command then there is just one place to update, not multiple places.

Answer



Solution:

Try calling it like this:

Artisan::call('app:cache --message="this is a command" --seconds=0');

and if you want to put dynamic variables in it:

Artisan::call('app:cache --message=' . $yourMessage . '--seconds=' . $seconds);

You will not have to handle any arrays by passing your variables in a single string line like this. It still makes it simple to read as a single string.

Source