#development #laravel #php #terminal
When outputting information on the command line, it quickly gets messy. An easy solution may be to add new lines to break up the output, but that doesn't provide context to the user. Adding some colors to the mix makes messages clear and adds emphasis to the output.
Laravel makes it easy to add colors to your output by using one of the default methods like
info. In this case, the
line method will be the default color. The
warn method will
show yellow text. The
error will display white text on a red background. The
question method displays black text on
a cyan background. Lastly, the
info method will display text in green.
1// Default color 2$this->line('This is a line'); 3 4// Yellow text 5$this->warn('This is a warning'); 6$this->comment('This is a comment'); 7 8// White text on red background 9$this->error('This is an error'); 10 11// Black text on cyan background 12$this->question('This is a question'); 13 14// Green text 15$this->info('This is some info');
Console colors are defined by the terminal itself. Green for example could be colored differently to what you expect, based on the settings in your terminal.
Laravel already offers some cool out-of-the-box options, but we can even take it a step further. When writing to the command line, we can define the foreground color, and the output's background color. Let's see how we can do that:
1$this->line('<bg=black> My awesome message </>'); 2$this->line('<fg=green> My awesome message </>'); 3$this->line('<bg=red;fg=yellow> My awesome message </>');
bg stands for background, while
fg stands for foreground (the text color).
Keep in mind that you might need to add extra spaces around the text to make it more readable because of the bold background color.
Apart from that, we can add more options like bold text to emphasize the output.
1$this->line('<options=bold;fg=red> MY AWESOME MESSAGE </>'); 2$this->line('<options=underscore;bg=cyan;fg=blue> MY MESSAGE </>');
We may pick one of the following colors:
default, and one of the following options for the font style:
reverse option can be handy to swap the background and foreground colors.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.