Stream Artisan command output to the browser using Livewire.

Updated: Jan 31, 2025

Stream Artisan command output to the browser using Livewire.

To stream Artisan command output to the browser using Livewire, you'll need to create a custom Livewire component and use Laravel's ArtisanFacade along with the process method to execute the command and capture its output. Here's a step-by-step guide to achieve this:

  1. Create a new Livewire component:
php artisan make:livewire StreamCommandOutput
  1. Open the newly created StreamCommandOutput.php file and add the following code:
namespace App\Http\Livewire;

use Livewire\Component;
use Artisan;
use Illuminate\Support\Facades\Artisan as FacadesArtisan;

class StreamCommandOutput extends Component
{
    public $output = '';

    public function streamCommandOutput()
    {
        $this->output = '';

        Artisan::call('command:name', function ($command) {
            $command->setSilent(false);

            $handle = fopen('php://output', 'w');
            stream_set_blocking($handle, false);

            $output = '';

            register_shutdown_function(function () use ($handle, &$output) {
                fwrite($handle, $output);
                fclose($handle);
            });

            set_error_handler(function ($severity, $message) use (&$output) {
                $output .= "Error: [$severity]: $message\n";
            });

            try {
                $command->handle();
            } catch (\Throwable $e) {
                $output .= "Error: " . $e->getMessage() . "\n";
            }

            $this->output .= $output;
        });
    }

    public function render()
    {
        return view('livewire.stream-command-output');
    }
}

Replace command:name with the name of your Artisan command.

  1. Create a new resources/views/livewire/stream-command-output.blade.php file and add the following code:
<div>
    <button wire:click="streamCommandOutput">Stream Command Output</button>

    <div>
        {{ $output }}
    </div>
</div>
  1. Register the component in app/Http/Kernel.php:
protected $components = [
    // ...
    App\Http\Livewire\StreamCommandOutput::class,
];
  1. Use the component in your route file or controller:
// routes/web.php
Route::get('/stream-command-output', StreamCommandOutput::class);

// app/Http/Controllers/HomeController.php
public function streamCommandOutput()
{
    return new StreamCommandOutput();
}

Now, when you visit the /stream-command-output route or call the streamCommandOutput() method in your controller, the Artisan command output will be streamed to the browser in real-time.