Brotzka Brotzka - 6 months ago 84
Bash Question

Laravel run composer / git commands within controller

is it possible to run composer or git commands from within a controller in Laravel? Something like that:

class TestController extends Controller
{
//
public function shell(Request $request){
if($request->isMethod('post')){


$data['output'] = shell_exec('composer update');
// or some git commands
return view('tests.shell', $data);
} else {
return view('tests.shell');
}
}
}


If I do it the way shown above, I get no message. I think, the problem is, that these commands have to be run in the projects root directory and not in an subfolder.

And is there a php function to run a complete shell script and not only single commands?

I have tested this:

echo shell_exec('php ' . __DIR__ . '/../shell.php');
// shell.php is in projects root directory


The script is executed, but not in the root directory.

Thanks!

Answer

I haven't noticed it before, but Laravel ships with a tool to run terminal commands/composer commands. You can use the The Process Component from Symfony. So it becomes very easy to run commands.

An example for Laravel 5.2:

namespace App\Http\Controllers;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;

use App\Http\Requests;

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

class SetupController extends Controller
{
    public function setup(){
        $migration = new Process("php artisan migrate");

        $migration->setWorkingDirectory(base_path());

        $migration->run();

        if($migration->isSuccessful()){
            //...
        } else {
            throw new ProcessFailedException($migration);
        }
    }
}