Home > Enterprise >  Arguments for Laravel command - how to define correctly?
Arguments for Laravel command - how to define correctly?

Time:10-16

In Laravel I have programmed a console command to do a database operation. The command should take two parameters: <single> and <plural>. The console command should look like: $ php artisan entities:make pagespeed_sample pagespeed_samples. This short program resides in a vendor package, installed by composer: https://packagist.org/packages/phitech/entities. When I tested it while it was still in the /routes/console.php of my laravel application, it worked correctly. But now after installing it as a package, it doesn't work. I do not know by the way whether I have perhaps changed anything inbetween to break it.

The program returns an error: "No arguments expected for "entities:make" command, got "pagespeed_sample".".

Why does it say it is not expecting any arguments? Also, when I try it without arguments, it returns the error: "Unable to resolve dependency [Parameter #0 [ $single ]] in class Illuminate\Foundation\Console\ClosureCommand".

Is there a way to explicitly define expected arguments for my command, besides having the arguments required in the callback?

The full code of this console command is found below. I am using Laravel Framework 9.35.1.

Artisan::command('entities:make', function ($single, $plural) {
    $entity_definition = json_encode([
        "entity_name" => $single,
        "main_db_table" => $plural,
        "meta_db_table" => $plural . "_meta",
        "meta_instance_id" => $single . "_id",
        "main_required_columns" => [$single . "_id"],
    ]);
    DB::table('entities')->insert([
        'name' => $single,
        'definition' => $entity_definition
    ]);
})->purpose('Register a new entity definition.');

CodePudding user response:

Closure command parameters need to be part of the command definition e.g.

Artisan::command('entities:make {single} {plural}', function ($single, $plural) {
    $entity_definition = json_encode([
        "entity_name" => $single,
        "main_db_table" => $plural,
        "meta_db_table" => $plural . "_meta",
        "meta_instance_id" => $single . "_id",
        "main_required_columns" => [$single . "_id"],
    ]);
    DB::table('entities')->insert([
        'name' => $single,
        'definition' => $entity_definition
    ]);
})->purpose('Register a new entity definition.');
  • Related