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

thebigk's avatar
Level 13

AlpineJS - Updating Button Text

I wish to update the button text upon click. However, for the initial load, the button status is determined by the value I have in database. Let me explain -

Blade -

<button>{{$status->active ? 'Deactivate' : 'Activate'}}</button>

Now, I'm aware that I can control this with AlpineJS as -

<div x-data="statusController">
<button x-text="status" @click="updateStatus()"></button>
</div>

<script>
function statusController() {
return {
  status = 'Activate',
updateStatus() {
this.status = "Deactivate" 
} 
}
}

But this approach does not allow me to set the button status when the page is loaded for the first time (i.e. status determined by the value from database).

Can someone guide? Thanks!

0 likes
8 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

How about

<div x-data="{status: '{{$status}}'">
1 like
thebigk's avatar
Level 13

@Sinnbeck - right. That makes sense. I was also wondering if I should make use of x-modelable.

thebigk's avatar
Level 13

@Sinnbeck . Never used it; so don't know for sure. Is there any way out if I'm defining x-data="someFunc()"? In this case, i can't pass my blade variables to JavaScript.

Sinnbeck's avatar

@thebigk sure you can do the same. As long as it's a blade file

<script>
function statusController() {
return {
  status = '{{$status}}',
thebigk's avatar
Level 13

@Sinnbeck - Does it work if my JS resides in a separate file? Is there any other way to do this?

Sinnbeck's avatar

@thebigk only if the file has access to the variable. So you need to pass it in

Another way is to use an ajax request (axios for instance)

thebigk's avatar
Level 13

@Sinnbeck Yep, ajax request. I think I'll have to fire a request right within the init(). Ok.

Please or to participate in this conversation.