Laravel Livewire 错误“初始化前不得访问”

Kou*_*tha 11 php initialization laravel eloquent laravel-livewire

我尝试使用 Livewire 直接绑定到模型属性,但收到此错误,有人可以帮忙吗?预先感谢。

初始化之前不得访问类型化属性 App\Http\Livewire\V2\Settings\Locations::$country

 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),
    ]);
  }
}
Run Code Online (Sandbox Code Playgroud)

Unf*_*lux 9

在 PHP 中定义变量的类型时,需要为其提供默认值。

如果您的组件正在创建,您可以在函数中将Country其设置为空:Countrymount

public function mount()
{
    $this->country = new Country();
}
Run Code Online (Sandbox Code Playgroud)

或者将 设为public Country $country现有的Country.