Search code examples
laravellaravel-artisanlaravel-scout

Executing Artisan command with arguments


Currently i'm facing following problem:

I want to update my search index automatically after my database has been updated. I've registered a saved() listener on my tables in AppServiceProvider:

\App\Customer::saved(function(\App\Customer $customer) {
    // Update search index here
 });

Inside the closure i try to call an Artisan command (scout:import) passing App\\Customer to the command. I've tried

Artisan::queue('scout:import', ['' => 'App\\\Customer']);
// Fails with message: Uninitialized string offset: 0

Artisan::queue('scout:import', ['model' => 'App\\\Customer']);
// Fails: Cannot redeclare class App\Customer

Artisan::queue('scout:import', ['App\\\Customer']);
// Fails: Not enough arguments (missing: "model")

I did'nt find information where to put the required arguments in the offical documentation.

I'm sure that it's dead simple (like everything in laravel) but i'm not able to get it done ...


Solution

  • The correct format is:

    Artisan::queue('email:send', [
        'user' => 1, '--queue' => 'default'
    ]);
    

    As per: https://laravel.com/docs/5.3/artisan#programmatically-executing-commands

    I'd say your middle example is probably closest, and is executing the command with the correct parameters, but there is something else going on under the surface.

    EDIT

    Just did a bit more digging, you need to refer to the signature of the Console command, which isn't actually apparent on the surface. In your case, you need to refer to this console command:

    https://github.com/laravel/scout/blob/2.0/src/Console/ImportCommand.php

    Note the signature is marked with {model}.

    So your command would look like:

    Artisan::queue('scout:import', ['model' => 'App\\\Customer']);
    

    Another example using the controller make command, note that this time we using the signature segment {name}:

    Artisan::call('make:controller', ['name'=>'FOOBAR']);
    

    Again, there is probably an underlying issue here - you should try running the import command from the console/terminal directly to see if you get the same issue.