laravel-livewire

Why Settings class is invalid after checkbox is clicked?


In laravel 11 / livewire 3.5 / mary-ui 1.35 app I have $appSettings class(Spatie\LaravelSettings\Settings class) which I define in mount as, where var $appSettings is set in mount method and used only in retrieveDbData method :

private AppGeneralSettings $appSettings;

//    public function mount(AppGeneralSettings $appSettings)
    public function mount()
    {
//        $this->appSettings = $appSettings; // The same error if uncomment this line and line at 3 rows above and comment the next line
        $this->appSettings = app(AppGeneralSettings::class);
        \Log::info(' -10 mount $this->appSettings::');
        \Log::info(json_encode($this->appSettings));

        $this->retrieveDbData();
    }

    protected function retrieveDbData(): void
    {
        \Log::info(' -18 retrieveDbData $this->appSettings::');
        \Log::info(json_encode($this->appSettings));
        ...
    }


    public function updated($property, $value)
    {
        if (\Str::substrCount($property, 'selectedCurrencies') > 0 ) { // Currency row selected/deselected
            $this->selectedCurrenciesLength = count($this->selectedCurrencies);
            $this->retrieveDbData();
        }
    }

Blade file of this component has checkbox with model selectedCurrencies for any row :

@foreach($currencies as $currency)

    <x-mary-list-item :item="$currency" no-separator no-hover>
        <x-slot:value>

            <x-mary-button>
                <x-mary-checkbox label="Select" id="selectedCurrencies_{{ $currency->id }}" wire:model.live="selectedCurrencies.{{ $currency->id }}" />
            </x-mary-button>

The problem is when a checkbox is checked I get the error:

Typed property App\Livewire\Home::$appSettings must not be accessed before initialization

and I see in the log file that in retrieveDbData method $this->appSettings var is empty and I can not catch why as I set it in the mount method and it works ok for the first time.

Checking the log I see that the mount method is called once and $this->appSettings var is not referenced in other places.

What is wrong?


Solution

  • The problem is in the first line of the code you posted:

    private AppGeneralSettings $appSettings;
    

    Livewire components do not inject dependencies into properties; they only inject them into methods. So, the approach you need to pursue is in your second line, which you've commented.

    public function mount(AppGeneralSettings $appSettings)
    

    For more details, see the dependecy injection notes in Livewire docs