How to inject Repository?

Hello, I have UserRepository class and UserRepositoryInterface for queries. I binded it in ServiceProvider and is it possible to use it in Livewire component?

public function __construct($id, UserRepositoryContract $userRepository)
 {
    parent::__construct($id);
    $this->userRepository = $userRepository;
}
1 Like

Are you trying to persist the state of the repository class, or can you new up a fresh instance on each request? Also, the code you posted, is that from your livewire component?

I have the same problem.

I think you can’t inject objects in the constructor. The LivewireManager instantiates the component only with the id.
You would have to inject the repository into the mount() function. This will be called once after the component was initiated.
But you would have to make the property public, because otherwise it wouldn’t be set again, after you, for example, call an action of the component.
Another solution would be to inject it into the action where you need it.

you can’t use the __constructor inside the Livewire Component, there is mount() method instead and you can work with it.

@skywalker is right, you need to use mount(), but you need to start with the object injection and then the variables.

Look at: https://laravel-livewire.com/docs/rendering-components#injecting-parameters