ahmd_rmzn's avatar

Scout indexing command is not functioning when executed from the controller.

The Scout import and flush commands work fine when executed via CLI, but they fail with a "command not found" error when executed from the controller.

Here is the command I attempted to run from the controller.

Artisan::call('scout:import', [ 'model' => "App\Models\Tag" ]);

0 likes
1 reply
LaryAI's avatar
Level 58

The issue you're encountering is likely due to the fact that the Artisan::call method requires the command name and its arguments to be passed in a specific format. Additionally, you should ensure that the Artisan facade is properly imported in your controller.

Here's a step-by-step solution to address the problem:

  1. Import the Artisan facade at the top of your controller file:

    use Illuminate\Support\Facades\Artisan;
    
  2. Modify the Artisan::call method to correctly pass the command and its arguments. The scout:import command expects the model class name as an argument, so you should pass it as a string without the array key.

Here is the corrected code snippet for your controller:

Artisan::call('scout:import', ['model' => 'App\\Models\\Tag']);

Note the double backslashes (\\) in the model namespace. This is necessary to properly escape the backslashes in the string.

  1. Ensure that the scout:import command is registered and available in your application. This is typically done in the App\Console\Kernel class, but since it works via CLI, this is likely already set up correctly.

Here is a complete example of how your controller method might look:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class TagController extends Controller
{
    public function importTags()
    {
        // Call the scout:import command for the Tag model
        Artisan::call('scout:import', ['model' => 'App\\Models\\Tag']);

        // Optionally, you can get the output of the command
        $output = Artisan::output();

        // Return a response or view
        return response()->json(['message' => 'Tags imported successfully', 'output' => $output]);
    }
}

This should resolve the "command not found" error and allow you to run the scout:import command from your controller.

Please or to participate in this conversation.