【问题标题】:Laravel Livewire error "must not be accessed before initialization"Laravel Livewire 报错“初始化前不能访问”
【发布时间】:2021-09-08 19:36:45
【问题描述】:

我尝试使用 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),
    ]);
  }
}

【问题讨论】:

    标签: php laravel eloquent initialization laravel-livewire


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 返回错误 validate country.name。谢谢
    • @KoungBuntha OK,所以你的验证失败了。
    • 是的,但是 wire:model="country.name" 值是有价值的。
    猜你喜欢
    • 2021-04-10
    • 2022-07-30
    • 2020-08-25
    • 2020-09-08
    • 2021-09-29
    • 2019-10-12
    • 2020-11-30
    • 2021-11-02
    • 2022-01-04
    相关资源
    最近更新 更多