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?
Aug 30, 2024
6
Level 6
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:
<?php
namespace App\Livewire\Forms;
use App\Enums\CourseType;
use App\Repositories\Interfaces\ICourseRepository;
use BenSampo\Enum\Rules\EnumValue;
use Exception;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
use Livewire\Component;
class Course extends Component
{
private ICourseRepository $_courses;
public $heading;
public $categories;
....
public function mount(ICourseRepository $courses, $heading = 'Add Course')
{
$this->_courses = $courses;
$this->heading = $heading;
}
...
public function create()
{
$this->reset(); // Reset all fields
$this->categories = $this->_courses->allCategories(); // Fetch all categories
$this->dispatch('openCourseModal', ['title' => 'কোর্স যোগ করুন']); // Dispatch an event to open the modal
}
...
public function render()
{
return view('livewire.forms.course');
}
}
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.
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.