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

thebookcollector's avatar

Double escaping issue with Alpine.js

I have an image gallery, it looks something like this:

var images = ['caption': '{{ $image->caption }}'];

I then display it in the blade with:

<p x-text="image.caption" class="text-sm lg:text-base overflow-scroll"></p>

Problem is, there seems to be double escaping going on for some reason. If a caption contains double quotes, for example (this is a "test" caption), I get this shown in the browser - this is a &quot;test&quot; captionand when I view the html in developer tools I see:

this is a &amp;quot;test&amp;quot; caption

instead of what I'd expect which is:

this is a &quot;test&quot; caption

I can change the first part to:

var images = ['caption': '{!! $image->caption !!}'];

and that works fine for double quotes - it displays everything fine (and correctly escapes stuff like <>) but then a single quote completely breaks the gallery. Gallery doesn't work and the caption doesn't show up.

Any ideas what is going on and what I can do to allow people to have double quotes and single quotes in their caption and still display correctly?

0 likes
4 replies
martinbean's avatar

@thebookcollector Your first code snippet doesn’t look correct, as you seem to be mixing the syntax for arrays and objects in JavaScript. Try just using Laravel’s Blade helpers for converting a PHP array to the JavaScript equivalent:

var images = @json($images);
<p x-text="image.caption"><!-- // --></p>
1 like
thebookcollector's avatar

@martinbean I should have clarified that in the first snippet I cut out irrelevant stuff but I am indeed putting other data and multiple items in the 'images' array.

I did also try @json but then it adds double quotes to the beginning and end of the caption which isn't want I wanted. I can certainly work with that though and just remove them after they are added, just wanted to see if there was another way I was missing. Thank you!

thebookcollector's avatar

Turns out I was way overcomplicating this. Simply doing this fixed everything:

var images = ['caption': '{!! addslashes($image->caption) !!}'];

Please or to participate in this conversation.