The right way to fix double encoding in Blade components

There is a lot of bad advice out there on this topic. Here's a better approach.

Joel Clermont
Joel Clermont

Recently, I burned more time than I'd like to admit trying to figure out why some data passed into a Blade component was being double-encoded.

For example, the value d'Angelo became d'Angelo in the view, but then became d'Angelo in the component. Notice how the & in the HTML entity ' was being encoded a second time. This is obviously not what I wanted.

If you search this topic on the internet, you'll see terrible advice like disabling "double encoding" altogether or using the raw syntax to echo data without escaping. These solutions might work, but they're far too broad and can introduce security issues.

Instead, by digging a little deeper, I realized none of these extreme measures were necessary. It turns out this is the expected behavior when you don't define the attribute in the component's constructor. The Laravel docs even hint at this.

Once I understood that, I stopped being so clever with the data attributes, and the fix was easy. I just had to add the data properties to the constructor of my Blade component.

<x-example :value="d'Angelo" /​>

// The original code which had the double-encoding issue didn't accept $value in the constructor
public function __construct()
    // no mention of the $value property

// By adding the $value property to the constructor, the double-encoding issue was resolved
public function __construct(public string $value) {}

Here to help,


P.S. Would you like a deeper understanding of how Laravel validation works and how to use it effectively in your app?

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.