Laravel Livewire error "must not be accessed before initialization"
Asked Answered
P

3

13

I try to using Livewire Binding Directly To Model Properties, and i get this error, Anyone help please ? Thank in advance.

Typed property App\Http\Livewire\V2\Settings\Locations::$country must not be accessed before initialization

 class Locations extends Component{
  public Country $country;
  use WithPagination;
  protected $rules = [
    'country.name' => 'required|min:100',
    'country.note' => 'required|min:100',
  ];

  public function SaveCountry(){
    $this->validate();
    $this->country->save();
    $this->reset();
    session()->flash('info','The country have been added successful.');
  }
 public function render(){
    return view('livewire.v2.settings.locations',[
        'countries' => Country::orderBy('order_num','desc')->paginate(10),
    ]);
  }
}
Perichondrium answered 25/6, 2021 at 11:43 Comment(0)
R
10

When you define the type of a variable in PHP, you need to provide it a default value.

If your component is creating a Country, you can set it to an empty Country in the mount function:

public function mount()
{
    $this->country = new Country();
}

Alternatively set the public Country $country to be an existing Country.

Rehash answered 25/6, 2021 at 11:46 Comment(3)
It return with error validate country.name. ThanksPerichondrium
@KoungBuntha OK, so your validation has failed.Rehash
Yes, But the wire:model="country.name" value was valued.Perichondrium
G
2

If for some reason Livewire keeps giving you the must not be accessed before initialization, even though you're using mount() as a replacement to __construct(), better use the boot() method that occurs even prior to mount().

It worked for me.

I finally understood it here: https://laravel-livewire.com/docs/2.x/lifecycle-hooks#class-hooks

Gearldinegearshift answered 11/5, 2023 at 0:7 Comment(1)
meta.stackexchange.com/a/8259/997587Respondent
G
0

Finally, I have rectified the issue by combining the __construct() and the mount() methods.

Below is the code sample.

    public Country $country;

    public function __construct()
    {
        // Initialize Product
        $this->country = new Country();
    }

    public function mount()
    {
        if ($this->country->exists) {
            dd('The "country" parameter has been set from the blade file.');
        } else {
            dd('Fresh Country instance.');
        }
    }
Guizot answered 14/10, 2023 at 6:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.