Search code examples
laraveleventslaravel-livewirealpine.js

Livewire magic actions not working Uncaught ReferenceError: $event is not defined


<div class="row">
    <div class="col">
        <div class="container">
            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col">
                            <div class="mb-5">
                                <label class="form-label">Order: </label>
                                <select wire:change="selectOrder($event.target.value)">
                                    @foreach($orders as $option)
                                        <option value="{{$option['id']}}">{{$option['id']}}</option>
                                    @endforeach
                                </select>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
public function selectOrder($order)
{
    $this->order = $order;
    $this->products = $this->order->products;
}

enter image description here

here is a live wire component that has a select input I need when changing the select the function selectOrder is executed with the selected value, i use $event magic action but i got the following error.


Solution

  • The $event is the Alpine.js magic property. So one way to solve it is to have use an Alpine.js event listener, that calls the Livewire method.

    <select x-on:change="$wire.selectOrder($event.target.value)">
    

    That said, you could use a property in the Livewire class, and bind the select to a model,

    <select wire:model="orderValue">
    

    And then in the component listen for that change.

    public $orderValue;
    
    // ...
    
    public function updated($field, $value)
    {
        if ($field === 'orderValue') {
            $this->selectOrder($value);
        }
    }