How To Get The Output Of An Artisan Command When Called Programmatically?

Arie Visser • September 1, 2020

laravel php

Sometimes you want to call an Artisan command from your code. Some commands show data. How do you read the data that an Artisan command may show in the console?

For example, you could have a command that lists all users of your application:

<?php

namespace App\Console\Commands;

use App\User;
use Illuminate\Console\Command;

class ListUsers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'list:users';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command will show a list of all users';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info(User::all());
    }
}

This command will show a collection of all users in your console.

You can call this command programmatically like this:

use Illuminate\Support\Facades\Artisan;

Artisan::call('list:users');

As you can see in the command, it will write the user collection to the console.

Symfony / Laravel makes it very easy to read this data, because the output of each command will be stored to a Symfony\Component\Console\Output\BufferedOutput object.

When you want to read this data, you can call:

use Illuminate\Support\Facades\Artisan;

Artisan::output();

Of course, you can also read the output of built-in Laravel commands, such as php artisan route:list.

The example code can be found in this repository.