Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ad45's avatar
Level 1

Binding $errors to x-data in AlpineJS

I have a very simple form that contains a file upload and displays any errors if the file is too large, is not a pdf, etc...

At the top of the blade file:

@php
    $hasFileError = $errors->has('file');
@endphp

<div x-data="{ hasError: {{ $hasFileError ? 1 : 0 }} }">

The problem is that $hasFileError obviously starts off as false, and when the user uploads a file and it fails validation, it comes back as true. Which it does, and when that happens, I check the DOM and see

but the value when I console.log(hasError), it shows 0.

Not sure what's going on at a deep level, but the data is not binding properly when Livewire performs a refresh.

Edit: The problem is because x-data is not run when the Livewire component is refreshed. How do I listen to the Livewire refresh event in Alpine?

@php
    $hasFileError = $errors->has('file');
@endphp

<div x-data="{ hasError: {{ $hasFileError ? 1 : 0 }} }"  x-init="Code to listen for livewire refresh">

Any help, can't seem to find it anywhere

0 likes
1 reply
Nakov's avatar

not sure if you are using Livewire 2 or 3, but here is the documentation for livewire 3.

https://livewire.laravel.com/docs/alpine#sharing-state-using-wireentangle

so instead of having the @php block within the blade view, create a variable in the livewire component itself and then use it in the view:

<div x-data="{ hasError: {{ $wire.entangle('hasFileError') }} }">

or use the dispatch event logic from the documentation that I shared and listen for the event in your view.

Please or to participate in this conversation.