0

How can I combine 2 functions in PHP?

I have 2 functions,

function #1

public function cache()
{
    $command = 'clear:cache';

    try {
        Artisan::call($command);
        $call = trim(Artisan::output());
        return back()->with('success', $call);
    } catch (\Exception $e) {
        Log::error('Problem running command: ' . $command);
        return back()->withErrors('error', ' There was a problem' . $e);
    }
}

function #2

public function staticCache()
{
    $command = 'clear:static';

    try {
        Artisan::call($command);
        $call = trim(Artisan::output());
        return back()->with('success', $call);
    } catch (\Exception $e) {
        Log::error('Problem running command: ' . $command);
        return back()->withErrors('error', ' There was a problem' . $e);
    }
}

I've tried this

public function cache()
{
    $commandClearCache = 'clear:cache';
    $commandClearStatic = 'clear:static';

    try {
        Artisan::call($commandClearCache, $commandClearStatic);
        $call = trim(Artisan::output());
        return back()->with('success', $call);
    } catch (\Exception $e) {
        Log::error('Problem running command: ' . $command);
        return back()->withErrors('error', ' There was a problem' . $e);
    }
}

But give me an error message: "Type error: Argument 2 passed to Illuminate\Foundation\Console\Kernel::call() must be of the type array, string given, called in /usr/share/nginx/html/statamic/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 217"

Thanks in advance for any help.

rurjaf
  • 45
  • 4
  • @VüsalHüseynli thats not what the error said, cause the error references to the second argument not the first – dnaumann Aug 12 '22 at 10:38

1 Answers1

0

Your first function is the same as the result of your tries, I think you copied the wrong function here. Nevertheless the second parameter of the Artisan::call function is for options not for a second Command.

You can either execute the Artisan::call function twice, one for each command you want to call like done here Custom Artisan Command to execute multiple commands. Or use Queueing https://laravel.com/docs/9.x/artisan#queueing-artisan-commands.

public function cache()
{
    $commands = ['clear:cache', 'clear:static'];
    $callResponse = '';

    foreach ($commands as $command) {
        try {
            Artisan::call($command);
            $callResponse .= trim(Artisan::output()) . PHP_EOL;
        } catch (\Exception $e) {
            Log::error('Problem running command: ' . $command);
            return back()->withErrors('error', ' There was a problem' . $e);
        }

        return back()->with('success', $callResponse);
    }
}
dnaumann
  • 444
  • 3
  • 13