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 AppLivewireForms;
use AppEnumsCourseType;
use AppRepositoriesInterfacesICourseRepository;
use BenSampoEnumRulesEnumValue;
use Exception;
use IlluminateSupportFacadesLog;
use IlluminateValidationRule;
use LivewireComponent;
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:
Error
PHP 8.3.4
10.48.20
Typed property AppLivewireFormsCourse::$_courses must not be accessed before initialization
Can you please help me get through this? Thank you for your attention.
2
Answers
If you look carefully at the error message you will get the reason behind this error:
Which means you need to initialize
$_courses
on the class constructor.You can simply make the
$_courses
property nullable to prevent initialization errors:So the initial value is null but later in the
mount
method it will get resolved using DI.The issue could be that your component is called many times in the application, but as specified in the livewire lifecycle hooks documentation, the
mount()
method is executed only once when the component is created, so when other actions are performed in the application, the service will no longer be injected, asmount()
will not be executed until the next page reload.If you need to use the
ICourseRepository
many times during the lifecycle of your Course component then you should inject it via theboot()
method that is called at the beginning of every request.Here’s an exemple :
I hope this will help