PHPackages                             henzeb/laravel-console-facade - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [CLI &amp; Console](/categories/cli)
4. /
5. henzeb/laravel-console-facade

ActiveLibrary[CLI &amp; Console](/categories/cli)

henzeb/laravel-console-facade
=============================

A convenient facade for interacting with the console

v1.19.0(2y ago)52.7k↓48.8%[1 issues](https://github.com/henzeb/laravel-console-facade/issues)AGPL-3.0-onlyPHPPHP ^8.1

Since Mar 15Pushed 2y ago1 watchersCompare

[ Source](https://github.com/henzeb/laravel-console-facade)[ Packagist](https://packagist.org/packages/henzeb/laravel-console-facade)[ Docs](https://github.com/henzeb/laravel-console-facade)[ RSS](/packages/henzeb-laravel-console-facade/feed)WikiDiscussions master Synced yesterday

READMEChangelog (10)Dependencies (5)Versions (34)Used By (0)

Console Output
==============

[](#console-output)

[![Build Status](https://github.com/henzeb/laravel-console-facade/workflows/tests/badge.svg)](https://github.com/henzeb/laravel-console-facade/actions)[![Latest Version on Packagist](https://camo.githubusercontent.com/7b1acc8a57a0acadc0bb96142b2dfd52ff2033caab4ecbd5f891783d20aa6bc1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68656e7a65622f6c61726176656c2d636f6e736f6c652d6661636164652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/henzeb/laravel-console-facade)[![Total Downloads](https://camo.githubusercontent.com/ba51e6eeba32ba9b87d33140cb7456164d0e4bf5cc9e7844a81ad2217a687212/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f68656e7a65622f6c61726176656c2d636f6e736f6c652d6661636164652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/henzeb/laravel-console-facade)[![Test Coverage](https://camo.githubusercontent.com/1f97d6f9c8ee9d21c20689f6e3dc74cf5f59dc6881d9078384959baa17cfe123/68747470733a2f2f6170692e636f6465636c696d6174652e636f6d2f76312f6261646765732f36346465313734616431653063323638303336312f746573745f636f766572616765)](https://codeclimate.com/github/henzeb/laravel-console-facade/test_coverage)[![License](https://camo.githubusercontent.com/5f97a45e94d8b948785bb3effb133c6afd715f6497dd62398b8e4ef417049212/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f68656e7a65622f6c61726176656c2d636f6e736f6c652d666163616465)](https://packagist.org/packages/henzeb/laravel-console-facade)

This package allows you to manage console output from places that are not directly inside the command classes.

As my applications require the logic not to be directly inside the command classes, I found myself adding the output to the constructors, creating real ugly not reusable code. This simplifies the process for me, and now for you.

Installation
------------

[](#installation)

Just install with the following command.

```
composer require henzeb/laravel-console-facade
```

Usage
-----

[](#usage)

Under the hood it uses the `InteractsWithIO` trait, so everything you can do with the output inside a command, you can use through the facade.

```
use Henzeb\Console\Facades\Console;
class MyClass {

    public function writeMessage(): void
    {
        Console::ask('Would you like to be able to do this?');
        Console::info('This message was brought to you by Henzeb');
    }
}
```

### console helper

[](#console-helper)

Instead of using the Console facade, you can also use the `console`helper method.

```
use function Henzeb\Console\Functions\console;

console('hello'); // outputs hello
console()->info('hello'); // outputs hello
console()->ask('Want an answer?'); // asks you a question
```

Note: Throughout the documentation the facade is used, but everything can be accessed with the helper method as well.

### Laravel's components factory

[](#laravels-components-factory)

Laravel released a new style for their commands, and they use a special Factory for that. With this method, you can use them within your own classes.

```
use Henzeb\Console\Facades\Console;
class MyClass {

    public function writeMessage(): void
    {
        Console::components()->ask('Would you like to be able to do this?');
        Console::components()->info('This message was brought to you by Henzeb');
        Console::components()->bulletList(['this one', 'Another one']);
    }
}
```

### Section management

[](#section-management)

The facade also allows you to manage and use sections. Inside the section you can only use the output methods from `InteractsWithIO` like `table`, `progressbar` or `info`, so that means asking questions cannot be done.

```
use Henzeb\Console\Facades\Console;
class MyClass {

    public function useSection(): void
    {
        Console::section()->table(['header'=>'title'], [[]]);
        Console::section('section2')->withProgressBar(100, fn()=>true);
        Console::section('section1')->components()->bulletList(['this one', 'Another one']);
        Console::section('section1')->clear();
        Console::section('section3')->info('This message was brought to you by Henzeb');
    }
}
```

When you do not pass a name, a `uniqid` will be given each time you call section. You can retrieve the name of this section by doing the following:

```
$section = Console::section();
$section->name(); //returns string similar to 64350abe27355
$section = Console::section('section1');
$section->name(); //returns section1
```

### delayed rendering

[](#delayed-rendering)

Delayed rendering is useful when you have to rebuild things from scratch, like a table, that takes a lot of time. With this, everything is generated first before outputting it to the console.

```
use Henzeb\Console\Facades\Console;

use Henzeb\Console\Output\ConsoleSectionOutput;

class MyClass {

    public function renderWhenReady(): void
    {
        Console::section()->render(
            function(ConsoleSectionOutput $section){
                $section->table(['header'=>'title'], [[]]);
            }
        );

        Console::section(
            'section2',
            function(ConsoleSectionOutput $section){
                $section->table(['header'=>'title'], [[]]);
            }
        );

    }
}
```

### replace

[](#replace)

The default `overwrite` method of Symfony is kinda slow when it comes to repeated rendering. If you find your console application is flickering, `replace` is a good `replacement`.

Note: `render`, `watch`, `tail` and the callback method on `section` are all using `replace`under the hood.

### watch

[](#watch)

`watch` is a method that mimics the `watch` command in Linux. By default, it will execute the given callback every 2 seconds.

```
Console::watch(
    function (ConsoleSectionOutput $output) {
        $output->info(now()->toDateTimeString());
    },
);
```

You can specify the refresh rate to speed up or slow down the loop.

```
Console::watch(
    function (ConsoleSectionOutput $output) {
        $output->info(now()->toDateTimeString());
    },
    1
);
```

It is also possible to specify the name for the section yourself. That way you can manipulate the section inside for example a `trap` signal.

```
Console::watch(
    function (ConsoleSectionOutput $output) {
        $output->info(now()->toDateTimeString());
    },
    sectionName: 'yourName'
);
```

### tail

[](#tail)

`tail` can be used to 'scroll' through added lines. Just like the linux command, `tail` shows you the last `n` lines.

```
Console::tail(); // returns a scrollable section with 10 lines
Console::tail(5); // returns a scrollable section with 5 lines
Console::tail(10, 'mySection'); // returns a scrollable mySection section

Console::section('mySection')->tail(10);
Console::section('mySection')->tail(10)->tail(5);//downgrades height to 5

Console::section('mySection')->setMaxHeight(10); // uses Symfony's implementation
Console::tail()->setMaxHeight(15); // upgrades height to 15
```

Inside Symfony's ConsoleSectionOutput, there is already a way of doing this, but there are numerous issues with. This implementation fixes them, and allows you to use any output, like progress bars and tables with ease.

You can still use Symfony's implementation on regular sections.

### exit

[](#exit)

Exit allows you to call exit anywhere in your code while making it easy to test.

```
Console::exit();
Console::exit(1);
```

#### exit hooks

[](#exit-hooks)

You can also add hooks that will execute when you call `exit`. Be aware that it does not register them as shutdown functions.

```
Console::onExit(
    function(int $exitcode) {
        Console::info('exited with code '.$exitcode);
    }
);

Console::onExit(
    function() {
        Console::info('exited with code 123');
    },
    123
);
```

### trap

[](#trap)

Just like Laravel, there is a `trap` method to register signals. Under the hood, this is not using the logic created by Laravel and Symfony for backwards compatibility reasons, but it's similar. See [\#43933](https://github.com/laravel/framework/pull/43933) for more information.

In below scenario, all three will run when a `SIGINT` signal is given and the second will also run when a `SIGTERM` signal is given. The first handler returns true. This means that when all handlers are executed, an exit is given.

```
Console::trap(
    function () {
        print('first handler');
        return true;
    },
    SIGINT
);

Console::trap(
    function () {
        print('second handler');
        var_dump(func_get_args());
        return false;
    },
    SIGINT,
    SIGTERM
);

Console::trap(
    function () {
        print('third handler');
    },
    SIGINT
);
```

#### Retrapping

[](#retrapping)

trap allows you to trap a new signal handler. This is useful when you want to be able to press `CTRL+C` twice. In the example below the next time the signal is received, the application will forcibly exit.

```
Console::trap(
    function () {
        print('first handler');

        Console::trap(
            function () {
                print('second handler');
                return true;
            },
            SIGINT
        );
    },
    SIGINT
);
```

Tip: When a handler was already registered the normal way or trough Laravel's implementation, you can use `pcntl_signal_get_handler` to pass this in to `trap`

Note: This was previously `onSignal`, but I have deprecated that method as Laravel is using `trap`.

#### untrap

[](#untrap)

Just like laravel, there is an untrap method. This method is automatically called just like the Laravel implementation, so you can use `Artisan::call`within your command and not execute the wrong signal handlers.

```
Console::untrap();
```

### Merging options and arguments

[](#merging-options-and-arguments)

In some cases you may want to merge options or arguments, like resuming a process with specific options or arguments stored in cache, or to reconfigure a running daemon process.

```
Console::mergeOptions(['env'=>'production']);

Console::mergeArguments(['yourArgument'=>true]);
```

When an option or argument is set through command line, that value will take precedence.

### optionGiven and argumentGiven

[](#optiongiven-and-argumentgiven)

In Laravel's `Command`, it can get pretty confusing to figure out if the user has specified an option or an argument. An option with optional parameter returns null either when set or not set. When you set a default, you could figure it out, but it is not really userfriendly and feels hacky instead of clean code.

The following methods tells you if a user has added the option or argument to the commandline

```
// artisan your:command --check --test=false
Console::optionGiven('check');   // returns true
Console::optionGiven('test');    // returns true
Console::optionGiven('verify');  // returns false

// artisan your:command verify
Console::argumentGiven('check');    //returns false
Console::argumentGiven('verify');   //returns true
```

Validation
----------

[](#validation)

Whether you build a console application that is going to be distributed, or just want to make sure no one can derail your application, you want to use validation. Laravel Console Facade makes that very easy to do.

Suppose you want to validate the input from the following signature:

```
{id?} {--name=} {--age=*} {--birth=}

```

Inside the `configure` method you simply define the following:

```
Console::validateWith(
    [
        'id' => 'bail|int|exists:users',
        '--name'=>'string|min:2',
        '--age.*' => 'bail|int|between:0,150',
        '--birth' => 'bail|prohibits:--age|date'
    ]
);
```

When running your command, the validation will automatically execute.

Under the hood, this uses Laravel's validation engine, so everything that the validation engine accepts, you can use here.

Caveat: When you want to validate options against arguments or options that may not be passed, you may need to write your own `Rule` or closure.

### Messages

[](#messages)

Since the translations are mainly based upon input coming from HTTP requests, you may want to give them different translations. Just add a second array like you would do with Laravel's validation engine:

```
Console::validateWith(
    [
        'id' => 'bail|int|exists:users',
        '--name' => 'string|min:2',
        '--age.*' => 'bail|exclude_with:--birth|int|between:0,150',
        '--birth' => 'bail|prohibits:--age|date',
    ],
    [
        'exists' => 'User with given id does not exist!'
        'prohibits' => 'Cannot be used together with :other'
    ]
);
```

### attribute names

[](#attribute-names)

Laravel allows you to rename attributes.

```
Console::validateWith(
    [
        'id' => 'bail|int|exists:users',
        '--name' => 'string|min:2'
    ],
    attributes: [
        'id' => 'user id',
        '--name' => 'name'
    ]
);
```

### value names

[](#value-names)

Just like attributes, you can also give certain values names.

Below we see an example where the accepted flag must be a form of `true`when any gender is specified.

```
Console::validateWith(
    [
        '--gender' =>'required|in:x,f,m',
        '--accepted' => 'accepted_if:--gender,x,--gender,f,--gender,m',
    ],
    valueNames: [
        '--gender' => [
            'm' => 'male',
            'f' => 'female',
            'x' => 'other gender'
        ]
    ]
);
```

### before validation callback

[](#before-validation-callback)

When you need access to the Validator instance before execution, you can use the `beforeValidation` method.

```
Console::beforeValidation(
    function(Illuminate\Validation\Validator $validator){
        // your logic
    }
);
```

### Closure based commands

[](#closure-based-commands)

When running `ClosureCommands` defined with `Artisan::command()` it does not validate automatically. Instead, you can do the following:

```
Artisan::command(
    'your:command {id?} {--name=} {--age=*} {--birth=}',
    function () {

        Console::validateWith(
            [
                //
            ]
        );

        Console::validate();

        //
    }
);
```

Verbosity
---------

[](#verbosity)

Console gives you an easy-to-use interface for handling verbosity insid your application.

```
Console::verbose('verbose'); // only prints `verbose` when -v or higher is passed.
Console::veryVerbose('very verbose'); // only prints `very verbose` when -vv or higher is passed.
Console::debug('debug'); // only prints `debug` when -vvv is passed.
```

These methods are using the following styles for coloring, which you can override if you wish.

StyleColorhenzeb.console.verbosecyanhenzeb.console.very.verboseyellowhenzeb.console.debugmagentaAdvanced Verbosity
------------------

[](#advanced-verbosity)

Next to simple lines, Console also allows you to use any available output methods.

```
Console::verbose()->info('info'); // only prints `info` when -v or higher is passed.

Console::debug()->ask('debug?'); // only asks when -vvv is passed, returns null otherwise

Console::veryVerbose()->ask('very verbose?', 'no'); // only asks when -vv or higher is passed, returns 'no' otherwise

Console::verbose()->withProgressbar(2, fn() => true); // only shows the progressbar when -v or higher is passed
```

Note: While the progressbar is not shown due to verbosity, the given callable is still executed. Also note that the [watch](#watch) will not run at all when the verbosity does not match.

### Verbosity and sections

[](#verbosity-and-sections)

The verbosity interface is also supported with sections.

```
Console::section('mySection')->debug('debug'); // only prints `debug` when -vvv is passed.
Console::section('mySection')->debug()->info('info');// only prints `info` when -vvv is passed.

Console::debug()->section('mySection')->info('info');// only prints `info` when -vvv is passed.
```

Note: be aware that verbose sections are the same as the non-verbose section. This means you can't just `clear` the verbose output inside a section as it will clear the entire section.

### silence

[](#silence)

Silence is a handy way to hide elements like progressbars based on a boolean.

```
Console::silence(false)->info('test'); // prints test
Console::silence(true)->info('test'); // prints nothing
Console::silence(false)->debug('test'); // prints test when -vvv is passed.
Console::silence(true)->debug('test'); // prints nothing, even when -vvv is passed.

Console::section('section')->silence(true)->info('test'); // prints nothing
Console::section('section')->silence(false)->info('test'); // prints test

Console::silence(true)->withProgressBar(5, fn()=>true); // runs the callback, but won't show progress
Console::silence(false)->withProgressBar(5, fn()=>true); // runs the callback, and shows progress
```

You can even chain silence so output will only be shown when a combination of parameters is given:

```
Console::silence(false)->silence(false); // shows output
Console::silence(true)->silence(false); // shows no output
Console::silence(false)->silence(true); // shows no output
Console::silence(true)->silence(true); // shows no output
```

### unsilence

[](#unsilence)

Unsilence is the direct opposite of `silence`.

```
Console::unsilence(true)->info('test'); // prints test
Console::unsilence(false)->info('test'); // prints nothing
Console::unsilence(true)->debug('test'); // prints test when -vvv is passed.
Console::unsilence(false)->debug('test'); // prints nothing, even when -vvv is passed.

Console::section('section')->unsilence(false)->info('test'); // prints nothing
Console::section('section')->unsilence(true)->info('test'); // prints test

Console::unsilence(false)->withProgressBar(5, fn()=>true); // runs the callback, but won't show progress
Console::unsilence(true)->withProgressBar(5, fn()=>true); // runs the callback, and shows progress
```

Note: Whatever you can do with `silence`, you can do with `unsilence`. You can even mix them up in chaining commands.

Macros
------

[](#macros)

The Console facade and `Henzeb\Console\Output\ConsoleSectionOutput` are Macroable using Laravel's Macroable trait.

```
Console::macro(...)
Henzeb\Console\Output\ConsoleSectionOutput::macro(...)
```

See [documentation](https://laravel.com/api/master/Illuminate/Support/Traits/Macroable.html)

Conditions
----------

[](#conditions)

You can use `when` and `unless` just like you are used to on the facade as well as inside sections. See [documentation](https://laravel.com/api/master/Illuminate/Support/Traits/Conditionable.html)

Testing
-------

[](#testing)

Next to the usual Facade test options, I have added some convenient methods for use inside your tests.

```
Console::shouldExit();
Console::shouldNotExit();
Console::shouldExitWith(int $seconds);
Console::shouldSleep();
Console::shouldNotSleep();
Console::shouldSleepWith(int $seconds);
Console::watchShouldLoop(int $times, int $sleep = null);
```

Testing this package
--------------------

[](#testing-this-package)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Henze Berkheij](https://github.com/henzeb)

License
-------

[](#license)

The GNU AGPLv. Please see [License File](LICENSE.md) for more information.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance16

Infrequent updates — may be unmaintained

Popularity25

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~22 days

Recently: every ~83 days

Total

33

Last Release

844d ago

PHP version history (3 changes)v1.0.0PHP ^7.4|^8.0

v1.14.0PHP ^8.0

v1.19.0PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/15928532?v=4)[henzeb](/maintainers/henzeb)[@henzeb](https://github.com/henzeb)

---

Top Contributors

[![henzeb](https://avatars.githubusercontent.com/u/15928532?v=4)](https://github.com/henzeb "henzeb (38 commits)")

---

Tags

consolelaravelfacadehenzeb

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/henzeb-laravel-console-facade/health.svg)

```
[![Health](https://phpackages.com/badges/henzeb-laravel-console-facade/health.svg)](https://phpackages.com/packages/henzeb-laravel-console-facade)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[nunomaduro/laravel-console-menu

Laravel Console Menu is an output method for your Laravel/Laravel Zero commands.

819430.4k54](/packages/nunomaduro-laravel-console-menu)[api-platform/laravel

API Platform support for Laravel

58171.4k14](/packages/api-platform-laravel)[sunaoka/laravel-facade-generator

Provide command line generation of facade layer files.

172.0k](/packages/sunaoka-laravel-facade-generator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
