im-nazmul's avatar

Dependency Injection is not working on any of my Livewire 3 components

I'm facing a very weird issue. Dependency injection is not working, and I don't have any clue why it isn't. Here's my component:

Here, the click method is bound to the wire:click event. The exception I'm encountering is:

Call to a member function allCategories() on null

Can you please help me get through this? Thank you for your attention.

0 likes
6 replies
im-nazmul's avatar

Ok, I found that the dependency injection does work. I used dd($this->_courses->allCategories()); inside the mount method, and I got the data. So why is it not working in the create method, even after assigning it to a public property?

shadkamel's avatar

make $_courses to public property and make sure pass courses as a ICourseRepository collection not an array.

1 like
im-nazmul's avatar

@shadkamel You can't use dependency injection (DI) directly on public property in Livewire because Livewire manages the state of public properties between requests by serializing and deserializing them during the component's lifecycle.

2 likes
im-nazmul's avatar
im-nazmul
OP
Best Answer
Level 6

I just resolved it per method injection for example:

public function create(ICourseRepository $_course)
{
       $this->reset(); // Reset all fields
       $this->categories = $_courses->allCategories(); // Fetch all categories
       $this->dispatch('openCourseModal', ['title' => 'কোর্স যোগ করুন']); // Dispatch an event to open the modal
}

Just like that, It works for me. Thank you everyone for allowing me some of your valuable time.

1 like

Please or to participate in this conversation.