Nested Data Binding in Laravel Livewire

Last updated 30/05/2020

Did you know that you can do nested data binding in Laravel Livewire? Here's how.

Laravel Livewire is a brilliant addition to any Laravel developer's toolkit. It takes a hot minute to get your head around, but once you have it, you can't put it down. Its like having the power of Vue or React, but with full access to the database, and written in the language of our Laravel hearts: PHP.

I've been playing with (and using in real world projects) Livewire for some time now. The documentation is truly awesome, so go check it out. One thing that the docs are a little vague on though, is nested data binding.

Here's a quick example of what I mean for the uninitiated.

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class PriceModelForm extends Component {

	// Here's our Livewire component

	public $flatData = 'biz'; // Here is a flat property
	public $groupOfData = []; // Keep an eye on this property
    
    public function mount() // This is where we can do any setup we require
    {
    	$this->groupOfData['foo'] = 'bar'; // Note that we're setting an associative value
    }
    
    // ... The rest of the component goes here

Super simple. Now let's look at the related blade view.

<div>
	<input wire:model="flatData" type="text"/> <!-- value === 'biz' -->
	<input wire:model="groupOfData.foo" type="text"/> <!-- value === 'bar' -->
</div>

Again, nothing special. This is, after all, just an example. Note, however, how easy it is to set up 2 way data binding, even on nested objects such as an associative array. Livewire uses the familiar dot syntax to access nested properties, and will responsibly keep the associative array in sync on the server-side.

Here's a thought though: how do you plug into lifecycle hooks for nested properties? This is straightforward for flat properties:

public function updatedFlatData($value)
{
	// Do something with the value
}

Well, you'll be stoked to find out that its also pretty simple for nested properties. The hook method should reference the base data, as if it were flat. It will receive the value as the first parameter. However, it passes in a second parameter. That second parameter is the key of the updated nested value. Here's an example:

public function updatedGroupOfData($value, $updatedKey)
{
	// $updatedKey === 'foo'
}

Of course, if you're not careful, this method could get pretty messy, pretty quickly. So, its your responsibility to delegate to other methods where necessary and keep everything clean and tidy.

Hopefully you've learned something useful here, and I hope you're loving using Livewire just as much as I am!