php - Livewire instance in variable sets itself null

in my laravel livewire component, i have this code.

private $wireAlertService;

public function mount() {
    $this->supervisors = User::getSupervisors();

    $this->wireAlertService = new LivewireAlertService();

    // dd($this->wireAlertService);
}

the commented out dd() dumps the instance of LivewireAlertService as wanted.

however, in other method, that fire's on button's wire:click, the variable $wireAlertService is null.

public function approveMany($attrs) {

    // code

    dd($this->wireAlertService, (new LivewireAlertService()));
    // $this->wireAlertService->success($this);
    // (new LivewireAlertService())->success($this);
}

in method approveMany() dd() dumps this

null
App\Services\LivewireAlertService {#2760}

therefore $this->wireAlertService->success($this); does not work (the desired one) while (new LivewireAlertService())->success($this); works, but i don't like it as much.

Answer

Solution:

As described within the introduction of Livewire, protected and private properties do not persist. Therefore, after your mount is completed, the property is reset.

If you wish to have it be persistent, you need to define it immediately, but this is not possible using a class instantiation, or make the property public.

Dependent on what the service is, you could inject it into each method, much like you would with the .

Source