【问题标题】:Laravel livewire property nested binding not showing the value in the form fieldLaravel livewire 属性嵌套绑定未显示表单字段中的值
【发布时间】:2021-01-12 09:26:53
【问题描述】:

我有一个用于显示个人资料信息的 livewire 组件。在我的表单中,我将值绑定到 wire:model 作为嵌套数据。但它没有在文本框中显示值。

组件

<?php

namespace App\Http\Livewire\Profile;

use Livewire\Component;

class BasicInfo extends Component
{
    public $user;

    public function mount()
    {
        $this->user = auth()->user();

    }
    
    public function render()
    {
        return view('livewire.profile.basic-info');
    }
}

刀片文件

<div class="container">
    <div class="row">
        <div class="col-12">
            <h1>{{ __('Profile Information') }}</h1>
        </div>
        <div class="col-6">
            <form>
                <div class="form-group row">
                    <label for="name" class="form-label">Name</label>
                    <input type="text" wire:model="user.name" class="form-control" disabled>
                </div>

                <div class="form-group row">
                    <label for="phone" class="form-label">Phone</label>
                    <input type="text" wire:model="user.phone" class="form-control" disabled>
                </div>

                <div class="form-group row">
                    <label for="location" class="form-label">Location</label>
                    <input type="text" wire:model="user.location.name" class="form-control" disabled>
                </div>
            </form>
        </div>
    </div>
</div>

当我在刀片文件中执行 dd($user) 时,它会正确返回用户对象。

当我直接将值分配给组件中的公共属性并在刀片中引用它时,它也在工作。

Laravel:8.x 火线:2.2

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    要使用wire:model Eloquent 属性绑定,您需要在组件上使用$rules 属性:

    protected $rules = [
        'user.name' => 'required',
        'user.phone' => 'required',
    ];
    

    此数组为组件上的字段设置默认验证规则,并充当可以绑定属性的白名单。

    关于您的user.location.name,Livewire 目前不支持这样的嵌套相关模型字段。您需要将 location 挂载到模型上的另一个属性并绑定到该属性。

    【讨论】:

    • user.location.name 也返回了预期值
    • 如果我的规则是这样的:'job.apply_type' =&gt; 'required|' . Rule::in(['link', 'email']),,PHP 不允许在属性值中添加它?我应该怎么做?
    猜你喜欢
    • 2015-09-02
    • 2013-06-05
    • 2021-09-10
    • 2021-01-11
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 2014-01-15
    • 2012-07-08
    相关资源
    最近更新 更多