How to echo to console in Laravel and Artisan?

前端 未结 7 1927
鱼传尺愫
鱼传尺愫 2021-02-03 21:02

I was curious, I\'m using Laravel and Artisan for my migrations. Is there a method to output information to the console? I can\'t seem to find any information on this. For examp

相关标签:
7条回答
  • 2021-02-03 21:50

    Don't know if you are using Laravel 3 or Laravel 4, and if its also possible in Laravel 3, but i found this in the docs.

    $this->info('Creating sample users...');
    

    EDIT

    If you switch to database seeds you can use this to display a message

    $this->command->info('Creating sample users...');
    
    0 讨论(0)
  • 2021-02-03 21:57

    Since the chosen answer doesn't seem to work since 4.2, I say just keep it simple:

    public function up() {
         // Migration runs //
         echo 'Records processed' . PHP_EOL;
    }
    
    0 讨论(0)
  • 2021-02-03 21:58

    I like the color added by the Dumper (tested on Laravel 5.3). I think looks a bit nicer than using the echo. The issue I have with the echo out is that it's too easy to be missed, the Dumper it adds a bit of green which catches ones eye:

    public function up() {
         // Migration runs //
         (new Illuminate\Support\Debug\Dumper)->dump("A bit more colorful text");
    }
    
    0 讨论(0)
  • 2021-02-03 21:58

    'Symfony\Component\Console\Output\ConsoleOutput;' works for me on Laravel 5.2

    0 讨论(0)
  • 2021-02-03 22:00

    Talking about Laravel 5 (you can check the version you have with php artisan --version), the Migration base-class has no printing method.

    A simple echo will do the work, However, if you want, you can extend it and add this functionality:

    abstract class MyMigration extends Migration
    {
        // colors for console echo
        protected const COLOR_RED = 'COLOR_RED';
        protected const COLOR_GREEN = 'COLOR_GREEN';
        protected const COLOR_YELLOW = 'COLOR_YELLOW';
    
        protected function logMessage($str, String $color = null)
        {
            switch ($color) {
                case self::COLOR_RED:
                    $str = "\033[01;31m$str\033[0m";
                    break;
                case self::COLOR_GREEN:
                    $str = "\033[01;32m$str\033[0m";
                    break;
                case self::COLOR_YELLOW:
                    $str = "\033[01;33m$str\033[0m";
                break;
    
                echo $str . PHP_EOL;
            }
        }
    }
    

    and then simply call it with your message:

    $this->logMessage("Your message", self::COLOR_RED );
    
    0 讨论(0)
  • 2021-02-03 22:02

    For database seeding in Laravel5, you can use

    $this->command->getOutput()->writeln("<info>Your message here</info>");
    

    to print the output on command line.

    <info> shows the message in green color where as <error> shows in red color which can be used for error messages.

    0 讨论(0)
提交回复
热议问题