Skip to content
Advertisement

Livewire wire:model not working with nested components

I’m creating a page using livewire to list users from DB and be able to update them.. I have a Users parent component and (User)s child components

users.blade.php:

<div>
    @foreach($users as $key => $user)
        <livewire:user :user="$user" key="{{$user->id}}">
    @endforeach
</div>

user.blade.php

<div>
    <form wire:submit.prevent="save">
        <input type="text" wire:model="user.name">
        <input type="text" wire:model="user.email">
        <button class="btn btn-info" type="submit">Save</button>
    </form>
</div>

Users.php

class Users extends Component
{
    public $users;
    
    public function mount()
    {
        $this->users = User::all();
    }

    public function render()
    {
        return view('livewire.users');
    }
}

User.php

class User extends Component
{
    public $user;

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

    public function render()
    {
        return view('livewire.user');
    }

    protected $rules = [
        'name' => 'required|min:6',
        'email' => 'required|email',
    ];

    public function save()
    {
        $this->validate();
        $user = $this->user;
        User::find($user['id'])->fill([
            'name' => $user['name'],
            'email' => $user['email']
        ]);
    }
}

This is what i’m getting in the browser

enter image description here

Any idea why this is happening ?

Advertisement

Answer

I found the issue, it was the validation rules, I had to change it to

protected $rules = [
    'user.name' => 'required|min:6',
    'user.email' => 'required|email',
];
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement