W
W
WebDev2016-08-16 15:06:26
Laravel
WebDev, 2016-08-16 15:06:26

Laravel how to inject a class?

Created a wrapper class over elasticsearch in App\Elastic.
In AppServiceProvider added to the register method

$this->app->singleton(App\Elastic\Elastic::class, function ($app) {
            return new App\Elastic\Elastic();
        });

Now how can I access it in the controller like this:
public function method(\App\Elastic\Elastic $elastic)
{
    $elastic->search(...);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Plisko, 2016-08-16
@AmdY

Everything seems to be correct, since you bind to a class, not an interface, you don’t even have to bother with $this->app->singleton, the controller method will have the necessary injection. Elsewhere, use the App::make and App::call methods

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question