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

TerrePorter's avatar

alpine set data issue

Hello,

I have a blade component that I pass data to that is a alpine component.

@props(['limit' => 255, 'update_key' => 'dead'])
<!-- https://rappasoft.com/blog/building-a-constrained-textarea-using-alpinejs -->
<div
        x-data="{
        limit: {{ $limit }},
        content: '{{ $slot }}',
        get remaining() {
            return this.limit - this.content.length
        }
    }"
>
    <textarea
            x-model="content"
            maxlength="{{ $limit }}"
        {{ $attributes }}
    >{{ $slot }}</textarea>
    <p>
        <small>You have <span x-text="remaining"></span> characters remaining.</small>
    </p>
    <button @click="$dispatch('spt', { key: '{{$update_key}}', content: content})" class="bg-blue-500 hover:bg-blue-700 text-white text-sm font-bold py-2 px-4 mb-2 rounded-full">
        Save
    </button>
</div>

I'm having a problem that when the $slot contains an apostrophe it dies.

Expression: "{
        limit: 1000,
        content: 'I'm hoping to find a friend...

I was thinking the blade tag would htmlspecialchar's the data but ...

Anyone have ideas on what to do to fix this?

0 likes
3 replies
LaryAI's avatar
Level 58

The issue you're facing is related to the use of apostrophes in the content of the $slot variable. To fix this, you can escape the apostrophes in the content using the addslashes function in PHP. Here's an example of how you can modify the code to fix the issue:

@props(['limit' => 255, 'update_key' => 'dead'])
<!-- https://rappasoft.com/blog/building-a-constrained-textarea-using-alpinejs -->
<div
    x-data="{
        limit: {{ $limit }},
        content: '{{ addslashes($slot) }}',
        get remaining() {
            return this.limit - this.content.length
        }
    }"
>
    <textarea
        x-model="content"
        maxlength="{{ $limit }}"
        {{ $attributes }}
    >{{ $slot }}</textarea>
    <p>
        <small>You have <span x-text="remaining"></span> characters remaining.</small>
    </p>
    <button @click="$dispatch('spt', { key: '{{$update_key}}', content: content})" class="bg-blue-500 hover:bg-blue-700 text-white text-sm font-bold py-2 px-4 mb-2 rounded-full">
        Save
    </button>
</div>

By using the addslashes function, any apostrophes in the content will be properly escaped, preventing any issues with the JavaScript code.

TerrePorter's avatar

that almost works, i now end up with ....

I&#039;m hoping to find 

Please or to participate in this conversation.