Home » Php » Laravel Lumen call artisan command from route

Laravel Lumen call artisan command from route

Posted by: admin November 30, 2017 Leave a comment

Questions:

In Laravel, I can do this to call an Artisan command from a route:

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

    //
});

But I can’t find an obvious way to do this in the Lumen framework. The error thrown is:

Fatal error: Class 'App\Http\Controllers\Artisan' not found
Answers:

This was actually very simple. Just be sure to use the Artisan Facade class wherever needed:

use Illuminate\Support\Facades\Artisan;
...
public function process()
{
    Artisan::call('command');
}

I assumed the normal Laravel facades weren’t available in the framework by default but they are.

Also, in bootstrap/app.php, $app->withFacades(); must be uncommented as @tptcat reminded me in the comments.

Questions:
Answers:

This is just an extension, maybe not the best way. But what if you just dont want to use the Facade way? Well you can do it via the Illuminate\Contracts\Console\Kernel.

// See what Artisan facade provides in `Illuminate\Support\Facades\Artisan`
// and thats: `Illuminate\Contracts\Console\Kernel`
app('Illuminate\Contracts\Console\Kernel')->call('command');

Or create an alias for the Illuminate\Contracts\Console\Kernel:

// In your service provider or bootstrap/app.php create the alias
$this->app->alias('arti', 'Illuminate\Contracts\Console\Kernel');

// now the 'artisan' alias is available in the container
app('arti')->call('command');