Error in laravel getting elasticsearch instance

Viewed 261

In my Laravel 5.7 application I want to use elasticsearch and I found this https://michaelstivala.com/learning-elasticsearch-with-laravel/ article. Firstly I wanted to import all data from a table I want to use with elasticsearch 1) I created a wrapper file app/Elastic.php, with content from githubusercontent. Is this proper dir for this file?

2) In my model app/Vote.php I added function

public static function bulkVotesToElastic() {

$elastic = app(App\Elastic\Elastic::class);

Vote::chunk(100, function ($Votes) use ($elastic) {
    foreach ($Votes as $Vote) {
        $elastic->index([
            'index' => 'select_vote',
            'type' => 'vote',
            'id' => $Vote->id,
            'body' => $Vote->toArray()
        ]);
    }
});

}

As I have seeder for filling of init data. But calling this method I got error:

Class App\App\Elastic\Elastic does not exist

Why error and how to fix it?

actually this line

$elastic = app(App\Elastic\Elastic::class);

is behind my laravel expierence...

Thanks!

1 Answers

Not so much a question about Laravel / Elasticsearch but about PHP namespacing and PSR-4 autoloading.

If you look at the composer.json file of your Laravel app you will find sth. like

"autoload": {
    "psr-4": {
        "App\\": "app/"
    }
}

Which means that you want to follow PSR-4 specification for namespaces inside your /app directory. Basically it means your folder structure must correspond to your namespace hierarchy.

Hence, Problem 1: You mention to have a class App\Elastic\Elastic inside /app/Elastic.php. This class cannot be loaded by your PSR-4 autoloader, it should be in /app/Elastic/Elastic.php OR be declared in the namespace App\.

Problem 2: When you call

$elastic = app(App\Elastic\Elastic::class);

inside a namespace, e.g. App/ it gets resolved to App/App as the error says. To avoid this, use \App\Elastic\Elastic::class as Anar proposes, or import the class via use statement.

Related