Search code examples
laravellaravel-artisan

Preserve linebreaks from Artisan::output in Laravel 9


My Controller code goes like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Artisan;

class ArtisanCommandController extends Controller
{
    public function artisan() {
        Artisan::call('print:datetime');
        print_r(Artisan::output());
    }
}

Command.php:

...
public function handle()
    {
        $date = date('Y-m-d H:i:s');
        $this->alert($date);
        return 0;
    }

When I run php artisan print:datetime in CMD, I get a nice line-breaked output of the actual time:

*******************************
*     2022-08-18 12:29:43     *
*******************************

But when I try to run it from Controller, it prints out as a one-line text:

******************************* * 2022-08-18 12:29:43 * *******************************

Is there a way to print it as a multiple-line text? When I do dd(Artisan::output());. I see all the \n line breaks..


Solution

  • When you run it in the controller you presumably see the results in the browser and the browser will not render CRLF as newlines. To have the browser show the text as "preformatted" you can wrap it in <pre> tags:

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Support\Facades\Artisan;
    
    class ArtisanCommandController extends Controller
    {
        public function artisan() {
            Artisan::call('print:datetime');
            return response('<pre>'.Artisan::output().'</pre>');
        }
    }