Skip to content

Working with arrays

Any time a user interacts with a component representing multiples of something, chances are those things are stored in an array.

Magewire provides a special syntax for working with individual items within arrays. It even works for manipulating nested arrays.

For the following examples, lets assume the we have this component with an array property:

class ArrayPropertyExample extends \Magewirephp\Magewire\Component
{
    public array $address = [
        'street' => 'Baggins Bvd. 2150',
        'city' => 'Hobbiton',
        'postcode' => '1',
        'country' => 'The Shire',
    ];
}

Binding to nested array keys

Targeting nested array keys is done using the dot notation:

<!-- The value will be 'Baggins Bvd. 2150' on initialization. -->
<input wire:model="address.street"/>
<!-- OR -->
<button wire:click="$set('address.street', 'Bag End')">Correct Street</button>

Array lifecycle hook methods

Lifecycle hook callback methods for nested properties are defined using camel case.
Continuing the above example, the matching method name would be updatedAddressStreet.

public function updatedAddressStreet(string $value): string
{
    return $value;
}