Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Lumen call artisan command from route

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
like image 200
Jared Eitnier Avatar asked Jan 04 '16 04:01

Jared Eitnier


People also ask

How do I run php artisan command in Lumen?

To see all built-in commands, use the php artisan command in Lumen. Although there is no make:command command at Lumen, you can create your custom command: Add new command class inside the app/Console/Commands folder, you can use the sample class template of the framework serve command.

How do you get artisan command in laravel?

To create a new artisan command, we can use the make:command artisan command. This command will make a new command class within the app/Console/Commands catalog. In case the directory does not exist in our laravel project, it'll be automatically made the primary time we run the artisan make:command command.


2 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.

like image 87
Jared Eitnier Avatar answered Oct 13 '22 15:10

Jared Eitnier


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');
like image 40
Yoram de Langen Avatar answered Oct 13 '22 15:10

Yoram de Langen