28
MarLaravel Console Toolkit is a package that makes it even easier to write maintainable and expressive Artisan commands, with argument/option casting, validation, and autoAsk. Also, it lets you define your arguments/options with simple properties and attributes for better ide support and static analysis. And all this with a single trait.
Here are some amazing features of Laravel Console Toolkit:
PHP-Attributes
to automatically define your inputs based on types–dry
or –no-dry
You can install the package via composer by running this command:
composer require thettler/laravel-console-toolkit
A Basic Command
To use the Toolkit you simply need to add the UsesConsoleToolkit
trait inside your command. Then add the Thettler\LaravelConsoleToolkit\Attributes\ArtisanCommand
to the class to specify the name and other things like description, help, and so on.
The ArtisanCommand
requires the name
parameter to be set. This will be the name of the Command which you can use to call it from the command line.
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Thettler\LaravelConsoleToolkit\Concerns\UsesConsoleToolkit;
#[ArtisanCommand(
name: 'basic',
)]
class BasicCommand extends Command
{
use UsesConsoleToolkit;
public function handle()
{
}
}
And call it like:
php artisan basic
Cast can be specified on Arguments
and Options
. You can either provide a class string of a caster to use or an instance of the caster. This is helpful to configure the caster via the constructor.
This package also offers:
You can also employ the normal laravel validation rules to validate the input.
#[Argument(
validation: ['max:5']
)]
protected string $validated;
If you want custom messages you need to use the Validation object
#[Argument(
validation: new \Thettler\LaravelConsoleToolkit\Transfers\Validation(
rules: ['max:5']
messages: [
'max' => 'This is way to much!'
]
)
)]
protected string $validated;
By default, Auto Ask is enabled. Every time a command is called with an input that fails validation or is required but not specified the command automatically asks the user to enter a (new) value. If the type is an enum it will give the user choice with all the enum values.
If you want to disable this behavior you can do it locally:
#[Argument(
autoAsk: false
)]
protected string $dontAsk;
or globally in your AppServiceProvider
:
\Thettler\LaravelConsoleToolkit\ConsoleToolkit::enableAutoAsk(false);
This package has many other features with code examples. If you want to explore more about this package you can visit its complete documentation and source code on Github.
Published at : 28-03-2022
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.
Launch project